Created
February 6, 2019 09:08
-
-
Save koma77/f76c8bb3db7ecf77631bb54151ebfdf1 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
import random | |
from queue import Queue | |
from threading import Thread | |
# A thread that produces data | |
def producer(out_q, num_threads): | |
for i in range(1,100): | |
# Produce some data | |
d = [] | |
d.append(i) | |
d.append(random.randint(1, 10)) | |
d.append(random.randint(1,10)) | |
out_q.put(d) | |
# stop workers | |
for i in range(num_threads): | |
q.put(None) | |
# A thread that consumes data | |
def consumer(in_q): | |
while True: | |
# Get some data | |
data = in_q.get() | |
if data is None: | |
break | |
print(data) | |
# gogogo | |
num_worker_threads = 10 | |
q = Queue() | |
threads = [] | |
for i in range(num_worker_threads): | |
t = Thread(target=consumer, args=(q,)) | |
t.start() | |
threads.append(t) | |
tp = Thread(target=producer, args=(q,num_worker_threads)) | |
tp.start() | |
for t in threads: | |
t.join() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment