python--多线程threading,thread包

多线程thread包,同时启动,可以缩短运行时间,注意只传一个参数的参数写法

import time
import _thread as thread
def loop():
    print(1)
def oppo():
    print(2)
def youcan(st):
    print(st)
def can(s,t):
    print(s,t)
def main():
    print("start at:",time.ctime())
    thread.start_new_thread(loop,())
    thread.start_new_thread(oppo,())
    thread.start_new_thread(youcan,("SWALLOW",))
    thread.start_new_thread(can,("SWALLOW","lili"))
    print("all done")
if __name__=="__main__":
    main()    

threading包的使用:

  1. treading.currentThread:返国当前线程变量
  2. threading.enumerate:返回一个包含正在运行的线程的List,
  3. threading.activeCount:返回正在运行的线程数量,效果跟Len(threading.enumerate )相同
  4. r.getName:得到线程的名字
  5. r.setName:设置线程的名字
import time
import threading
def youcan(st):
    print(st)
def can(s,t):
    print(s,t)
def main():
    print("start at:",time.ctime())
    t1=threading.Thread(target=youcan,args=("SWALLOW",))
    t2=threading.Thread(target=can,args=("SWALLOW","lili"))
    t1.start()
    t2.start()
    t1.join()
    t2.join()#等待多线程执行完毕
    print("all done")
if __name__=="__main__":
    main()    

守护线程daemon:如果在程序中将子线程设置成守护线程,则子线程会在主线程结束时主动退出执行

生产者消费者问题:

import threading
import time
import queque
class Producer(threading.Thread):
    def run(self):
        global queue
        count=0
        while True:
            if queue.qsize()<1000:
                for i in range(100):
                    count=count +1
                    msg="生成产品"+str(count)
                    queue.put(msg)
                    print(msg)
                time.steep(0.5)
class Consumer(threading.Thread):
    def run(self):
        global queue
        while True:
            if queue.qsize()> 100:
                for i in range(3):
                    msg=se1f.name+'消费了:'+ queue.get()
                    print(msg)
                time.sleep(1)
if __name__="__main__":
    queue=queue.Queue()
    for i in range(500):
        queue.put("初始产量"+str(i))
    for i in range(2):
        p=Producer()
        p.start()
    for i in range(5):
        c=Consumer()
        c.start()

解决共享变量问题:锁

import threading
sum=0
loopsum=1000
lock=threading.lock()
def add():
    global sum,loopsum
    for i in range(1,loopsum):
        lock.acquire()
        sum+=i
        lock.release()
def dec():
    global sum,loopsum
    for i in range(1,loopsum):
        lock.acquire()
        sum-=i
        lock.release()
def main():
    print("start at:",time.ctime())
    t1=threading.Thread(target=add,args=())
    t2=threading.Thread(target=dec,args=())
    t1.start()
    t2.start()
    t1.join()
    t2.join()#等待多线程执行完毕
    print("all done")
if __name__=="__main__":
    main()    

 thread.Timer(6,fun):每隔6秒执行下fun函数

 

你可能感兴趣的:(Python)