Skip to content

Instantly share code, notes, and snippets.

@marklit
Created November 1, 2011 14:27
Show Gist options
  • Save marklit/1330624 to your computer and use it in GitHub Desktop.
Save marklit/1330624 to your computer and use it in GitHub Desktop.
Threading and queues in Python
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
@marklit
Copy link
Author

marklit commented Nov 1, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment