標籤:int import port lse random data out ... 啟動
# -*- coding: UTF-8 -*-"""多線程同時讀隊列總結: 1. 會阻塞 if self._jobq.qsize() > 0 進入邏輯,此時被其他線程把資料取完了, 在data = self._jobq.get() 阻塞 2. 需要學習鎖使用邏輯: * 主線程提前往隊列寫好所有資料 * 子線程讀取隊列資料,沒有就退出線程"""import Queueimport threadingimport timeimport randomq = Queue.Queue(0) # 無限大小的隊列NUM_WORKERS = 3 # 線程數量class MyThread(threading.Thread): """從隊列讀取資料列印""" def __init__(self,queue,worktype): """ :param queue: 隊列 :param worktype: 其他參數 """ threading.Thread.__init__(self) self._jobq = queue self._work_type = worktype def run(self): while True: if self._jobq.qsize() > 0: time.sleep(random.random() * 3) # 擷取隊列資料 data = self._jobq.get() print "doing",data," worktype ",self._work_type else: print "%d,end" % self._work_type breakif __name__ == ‘__main__‘: print "begin...." # 往隊列寫資料 for i in range(NUM_WORKERS * 2): q.put(i) print "job qsize:",q.qsize() # 啟動線程 for x in range(NUM_WORKERS): MyThread(q,x).start() print "end"‘‘‘Out:begin....job qsize: 6enddoing 0 worktype 1doing 1 worktype 0doing 2 worktype 2doing 3 worktype 1doing 4 worktype 2doing 5 worktype 00,end阻塞 ......‘‘‘
python 歸納 (十三)_隊列Queue在多線程中使用