Advertisement
rfmonk

queue.py

Apr 7th, 2014
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. #!/usr/bin/env
  2.  
  3. from Queue import *
  4. from threading import Thread, Lock
  5.  
  6.  
  7. #  this function will process the
  8. #  items in the queue, in serial
  9.  
  10. def processor():
  11.     if queue.empty() == True:
  12.         #  comparison to True should
  13.         #  be 'if cond is True:' or
  14.         #  'if cond:' [pep8]
  15.         print "Queue Empty"
  16.         sys.exit(1)
  17.  
  18.     try:
  19.         job = queue.get()
  20.         print "I'm operating on job item: %s" % (job)
  21.         queue.task_done()
  22.     except:
  23.         print "Failed to work on job"
  24.  
  25. #  set variables
  26. queue = Queue()
  27. threads = 4
  28.  
  29. #  your list of job items
  30. jobs = ["job1", "job2", "job3"]
  31.  
  32. #  iterate over jobs and put each into
  33. #  the queue in sequence
  34. for job in jobs:
  35.     print "Adding job to queue: %s" % (job)
  36.     queue.put(job)
  37.  
  38. #  start threads, each one will process
  39. #  one job from the queue
  40. for i in range(threads):
  41.     th = Thread(target=processor)
  42.     th.setDaemon(True)
  43.     th.start()
  44.  
  45. #  wait untill all jobs are processed before quitting
  46. queue.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement