多线程中同步-异步---生产者与消费者-Queue---ThreadLocal实现局部变量保存

来源:互联网 发布:mac隐藏照片 编辑:程序博客网 时间:2024/05/29 08:07

同步:协同步调,按次序执行

异步:互相不等待,没有顺序

python2与python3中queue引用的模块不同


多线程中生产者与消费者

#encoding=utf-8import threadingimport time#python2中from Queue import Queue#python3中# from queue import Queueclass 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.sleep(0.5)class Consumer(threading.Thread):    def run(self):        global queue        while True:            if queue.qsize() > 100:                for i in range(3):                    msg = self.name + '消费了 '+queue.get()                    print(msg)            time.sleep(1)if __name__ == '__main__':    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()
ThreadLocal实现局部变量保存

import threading# 创建全局ThreadLocal对象:local_school = threading.local()def process_student():    # 获取当前线程关联的student:    std = local_school.student    print('Hello, %s (in %s)' % (std, threading.current_thread().name))def process_thread(name):    # 绑定ThreadLocal的student:    local_school.student = name    process_student()t1 = threading.Thread(target= process_thread, args=('dongGe',), name='Thread-A')t2 = threading.Thread(target= process_thread, args=('老王',), name='Thread-B')t1.start()t2.start()t1.join()t2.join()
全局变量local_school就是一个ThreadLocal对象,每个Thread对它都可以读写student属性,但互不影响。你可以把local_school看成全局变量,但每个属性如local_school.student都是线程的局部变量,可以任意读写而互不干扰,也不用管理锁的问题,ThreadLocal内部会处理。

原创粉丝点击