Created
November 1, 2011 14:27
-
-
Save marklit/1330624 to your computer and use it in GitHub Desktop.
Threading and queues in Python
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 threading, Queue, time, random | |
WORKERS = 4 | |
JOB_COUNT = 100 | |
class Worker(threading.Thread): | |
def __init__(self, queue): | |
self.__queue = queue | |
threading.Thread.__init__(self) | |
def run(self): | |
while 1: | |
item = self.__queue.get() | |
if item is None: | |
break # reached end of queue | |
# pretend we're doing something that takes 10-100 ms | |
time.sleep(random.randint(10, 100) / 1000.0) | |
print "task", item, "finished" | |
queue = Queue.Queue(0) | |
for i in range(WORKERS): | |
Worker(queue).start() # start a worker | |
for i in range( JOB_COUNT ): | |
queue.put(i) | |
for i in range(WORKERS): | |
queue.put(None) # add end-of-queue markers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This came from http://effbot.org/librarybook/queue.htm