Skip to content

Instantly share code, notes, and snippets.

@meganlkm
Created May 19, 2020 18:33
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 meganlkm/0710afa56789fe878878d5cd750baf8f to your computer and use it in GitHub Desktop.
Save meganlkm/0710afa56789fe878878d5cd750baf8f to your computer and use it in GitHub Desktop.
Thread/Queue Example
import random
import time
from queue import Queue
from threading import Thread
WORKERS = 2
class Worker(Thread):
def __init__(self, queue):
self.__queue = queue
Thread.__init__(self)
def run(self):
while 1:
item = self.__queue.get()
if item is None:
# reached end of queue
break
# pretend we're doing something that takes 10-100 ms
time.sleep(random.randint(10, 100) / 1000.0)
print(f"task {item} finished")
q = Queue(3)
for i in range(WORKERS):
# start a worker
Worker(q).start()
for item in range(10):
print(f"push {item}")
q.put(item)
for i in range(WORKERS):
# add end-of-queue markers
q.put(None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment