Skip to content

Instantly share code, notes, and snippets.

@cshuaimin
Last active September 4, 2018 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cshuaimin/2fb314863783b29b186bb18291b1e7a0 to your computer and use it in GitHub Desktop.
Save cshuaimin/2fb314863783b29b186bb18291b1e7a0 to your computer and use it in GitHub Desktop.
from threading import Thread
from queue import Queue
from time import sleep
queue = Queue(maxsize=4)
EXIT_FLAG = object()
def producer():
for i in range(10):
print(f'Adding {i} to the queue..')
queue.put(i)
print('Producer done.')
queue.put(EXIT_FLAG)
def consumer(id):
while True:
data = queue.get()
if data == EXIT_FLAG:
print(f' Consumer {id} done.')
# The remaining consumers will never exit if you comment this line.
queue.put(EXIT_FLAG)
break
print(f' [{id}] Consuming {data}..')
# Simulate time-consuming operation
sleep(.2)
Thread(target=producer).start()
threads = []
for i in range(3):
t = Thread(target=consumer, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
assert(queue.qsize() == 1)
@zh-h
Copy link

zh-h commented May 10, 2018

queue.get()是阻塞的,不需要再sleep啊

@cshuaimin
Copy link
Author

@zh-h 只有 28 行有一个 sleep,是用来模拟处理数据时消耗的时间的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment