# Python Version: 2.7
import time
import threading
import thread
from Queue import Queue
# Global Queue
q = Queue()
num_worker_threads = 2
# worker to get item/message from the queue and process it.
def worker(q):
while True:
print("Waiting for Message ...{thread}\n".format(thread=thread.get_ident()))
item = q.get()
print("Message received...{thread}...{msg}\n".format(msg=item, thread=thread.get_ident()))
if item is None:
q.task_done()
print("Stop worker!")
break
do_work(item)
q.task_done()
#function to process message
def do_work(item):
print("Processing Message ...{thread}...{msg}\n".format(msg=item, thread=thread.get_ident()))
print("sleep 5s...")
time.sleep(5)
print("Message Processed...{thread}..{msg}\n".format(msg=item, thread=thread.get_ident()))
# start worker threads
threads = []
for i in range(num_worker_threads):
t=threading.Thread(target=worker, args=(q,))
t.start()
threads.append(t)
# Add items to the Queue
for item in ["AA", "BB", "CC"]:
q.put(item)
# Stop all workers
for i in range(num_worker_threads):
q.put(None)
网友评论