from queue import Queue from datetime import datetime import threading import os,sys q = Queue() fileprefix = 'test' def creator(): for i in range(1, 100): q.put_nowait(i) print('creator: put - ', i, 'size:', q.qsize()) def getor(): while True: try: result = q.get(block=True, timeout=5) if result: writelog(str.format('getor: get-{0},size:{1}', result, q.qsize())) q.task_done() #告诉队列完成一项任务,增加任务计数 if q.empty(): print('reset singal') except Exception as e: print(e) def writelog(logmsg): filename = fileprefix + '.' + str(datetime.now().date()) + '.log' if not os.path.exists(filename): with open(filename, 'w'):pass with open(filename, 'a+') as fp: fp.write(logmsg + ' ') t1 = threading.Thread(target=creator) t2 = threading.Thread(target=getor) t1.start() t1.join() t2.setDaemon(True) # 队列任务结束,结束队列循环 t2.start() print('阻塞队列') q.join() #等待队列任务完成 print('队列为空')