Skip to content

Instantly share code, notes, and snippets.

@koma77
Created February 6, 2019 09:08
Show Gist options
  • Save koma77/f76c8bb3db7ecf77631bb54151ebfdf1 to your computer and use it in GitHub Desktop.
Save koma77/f76c8bb3db7ecf77631bb54151ebfdf1 to your computer and use it in GitHub Desktop.
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