fork download
  1. from thread import start_new_thread
  2. from time import time, ctime, sleep
  3. from threading import Thread, Lock
  4. #from Queue import Queue
  5.  
  6. class Queue(object):
  7. def __init__(self):
  8. self.store = []
  9.  
  10. def put(self, value):
  11. self.store.append(value)
  12.  
  13. def get(self):
  14. return self.store.pop(0)
  15.  
  16. def empty(self):
  17. return not self.store
  18.  
  19.  
  20. class SyncQueue(Thread):
  21. __lock = Lock()
  22.  
  23. def __init__(self, name, delay, queue):
  24. Thread.__init__(self)
  25. self.name = name
  26. self.delay = delay
  27. self.queue = queue
  28.  
  29. def run(self):
  30. print "Starting %s" % self.name
  31. while not self.queue.empty():
  32. with self.__lock:
  33. print "%s got %s" \
  34. % (self.name,
  35. self.queue.get())
  36. sleep(self.delay)
  37. while not job_done:
  38. sleep(self.delay)
  39. print "Exiting %s" % self.name
  40.  
  41. def print_time(thread, delay):
  42. for i in xrange(3):
  43. sleep(delay)
  44. print "%s woke up at %s" % (thread, ctime(time()))
  45.  
  46. if __name__ == "__main__":
  47. job_done = False
  48. #q = Queue(5) # Python's Queue
  49. q = Queue() # Custom Queue
  50. for i in xrange(5):
  51. q.put(i)
  52. q1 = SyncQueue("Q1", 2, q)
  53. q2 = SyncQueue("Q2", 1, q)
  54. q1.start()
  55. q2.start()
  56.  
  57. # Wait for the job to be done
  58. while not q.empty():
  59. pass
  60. job_done = True
  61. q1.join()
  62. q2.join()
  63. print "All done!"
  64.  
Success #stdin #stdout 2.11s 27512KB
stdin
Standard input is empty
stdout
Starting Q1
Q1 saw 0 and got 0
Starting Q2
Q2 saw 1 and got 1
Q2 saw 2 and got 2
Q1 saw 3 and got 3
Q2 saw 4 and got 4
Exiting Q2
Exiting Q1
All done!