使用Python多線程實現生產者與消費者模型
阿新 • • 發佈:2018-07-02
watermark vpd 51cto 實現 this read sleep get DG 1,我所使用到的python版本
count =0
while count <=20:
resulte =q.get()
print ‘the thread name is %s and the consume num is %s‘ %(name,result)
time.sleep(4)
2,下面編寫具體的實現過程
import threading
import time
import Queue
#首先生成一個隊列
q =Queue.Queue()
#生產者
def producer(name):
l=threading.Rlock()
for i in range(40):
l.acquire()
q.put(i)
l.release()
print "this is thead name is %s ,produce num is %s" %(name,i)
time.sleep(2)
#消費者
def consumer(name):
while count <=20:
resulte =q.get()
print ‘the thread name is %s and the consume num is %s‘ %(name,result)
time.sleep(4)
#測試
for i in range(10):
p = threading.Thread(target=producer,args=(‘xxxx‘,))
p.start()
c =threading.Thread(target=consumer,args=(‘yyyy‘,))
c.start()
使用Python多線程實現生產者與消費者模型