7/13/2021python 核心编程02-02-15
生产者与消费者的解耦问题:
耦合时代码之前联系性很强,不好
解耦: 减少之间的联系
所以第一版本就要想的长远一点
这个例子使用队列作为缓冲部分
#encoding=utf-8
import threading
import time
from queue import Queue
class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
if queue.qsize()<1000:
count = count +1
msg = '生产产品'+str(count)
queue.put(msg)
print(msg)
time.sleep(1)
class Consumer(threading.Thread):
def run(self):
global queue
count = 0
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=('laowang',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
Result:
hello, dongge (in Thread-A)
hello, laowang (in Thread-B)