defworker(): whileTrue: item = my_queue.get() if item isNone: break # 处理任务... print(f"Processing: {item}, now queue_size:{my_queue.qsize()}") # time.sleep(0.1) my_queue.task_done()
t1 = time.time()
# 创建并启动多个工作线程 for _ inrange(3): threading.Thread(target=worker).start()
# 向队列中添加任务 for i inrange(9): my_queue.put(i)
print(f"work over")
# 等待所有任务完成 my_queue.join()
# 停止工作线程 for _ inrange(3): my_queue.put(None)
t2 = time.time()
print(f"Both threads have finished. total time: {t2-t1}")
输出结果
plaintext
1 2 3 4 5 6 7 8 9 10 11
work overProcessing: 0, now queue_size:8 Processing: 1, now queue_size:7
Processing: 2, now queue_size:6 Processing: 3, now queue_size:5 Processing: 4, now queue_size:4 Processing: 5, now queue_size:3 Processing: 6, now queue_size:2 Processing: 7, now queue_size:1 Processing: 8, now queue_size:0 Both threads have finished. total time: 0.0009996891021728516