import threading,queue,time
numproducer=4
nummessages=4
numconsumer=2
dataQueue=queue.Queue()
safeprint=threading.Lock()
def producer(i,dataQueue):
for msg in range(nummessages):
dataQueue.put('[producer id=%d,msg=%d]' %(i,msg))
def consumer(i,dataQueue):
while True:
try:
data=dataQueue.get(block=False)
except queue.Empty:
pass
else:
with safeprint:
print('consumer',i,'get==>',data)
if __name__=='__main__':
for i in range(numconsumer):
thread = threading.Thread(target=consumer,args=(i,dataQueue))
thread.daemon = True
thread.start()
#threads=[]
for i in range(numproducer):
thread = threading.Thread(target=producer,args=(i,dataQueue))
#threads.append(thread)
thread.daemon = True
thread.start()
#for thread in threads: thread.join()
time.sleep(1)
print('main thread exiting')
代码笔记 | 多线程使用queue模块同步访问共享数据
最新推荐文章于 2024-01-08 00:05:07 发布
本文通过Python实现了一个包含多个生产者和消费者的多线程消息队列示例。该示例展示了如何使用线程和队列进行进程间通信,并确保了线程安全的数据打印。
2783

被折叠的 条评论
为什么被折叠?



