python thread – 2

Another python threading implementation

import threading
import random
import signal
import queue
import time

work_queue = queue.Queue()
is_running = True

def consumer():
  while is_running:
    task = work_queue.get()
    print("doing: {}".format(task))
    
def producer():
  while is_running:
    task = random.random()
    work_queue.put(task)
    time.sleep(10*random.random())

def shutdown():
  print("terminating...")
  is_running = False
  
def main():
  print("starting two threads")
  t1 = threading.Thread(target=consumer, name="consumer")
  t2 = threading.Thread(target=producer, name="producer")
  
  signal.signal(signal.SIGINT, shutdown)
  
  t1.start()
  t2.start()
  
  t1.join()
  t2.join()
  
  print("bye")

  
if __name__ == "__main__":
  main()

Previous implementation: http://hong.ddns.net/wp-admin/post.php?post=164&action=edit

Posted in notesTagged , ,