Created
May 19, 2020 18:33
-
-
Save meganlkm/0710afa56789fe878878d5cd750baf8f to your computer and use it in GitHub Desktop.
Thread/Queue Example
This file contains 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 | |
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