Last active
September 4, 2018 06:26
-
-
Save cshuaimin/2fb314863783b29b186bb18291b1e7a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
queue.get()是阻塞的,不需要再sleep啊