代碼筆記 | 多線程使用queue模塊同步訪問共享數據

 
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')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章