python queue
http://www.learn4master.com/programming-language/python/python-queue-for-multithreading
http://link.zhihu.com/?target=http%3A//www.dongwm.com/archives/%25E4%25BD%25BF%25E7%2594%25A8Python%25E8%25BF%259B%25E8%25A1%258C%25E5%25B9%25B6%25E5%258F%2591%25E7%25BC%2596%25E7%25A8%258B-%25E7%25BA%25BF%25E7%25A8%258B%25E7%25AF%2587/
import threading
import time
import queue
def consume(q):
while True:
name = threading.current_thread().getName()
print("Thread: {0} start get item from queue[current size = {1}] at time = {2} \n".format(name, q.qsize(),
time.strftime(
'%H:%M:%S')))
item = q.get()
time.sleep(3)
print("Thread: {0} finish process item from queue[current size = {1}] at time = {2} \n".format(name, q.qsize(),
time.strftime(
'%H:%M:%S')))
q.task_done()
def producer(q):
for i in range(10):
name = threading.current_thread().getName()
print("Thread: {0} start put item into queue[current size = {1}] at time = {2} \n".format(name, q.qsize(),
time.strftime(
'%H:%M:%S')))
item = "item-" + str(i)
q.put(item)
print("Thread: {0} successfully put item into queue[current size = {1}] at time = {2} \n".format(name, q.qsize(),
time.strftime(
'%H:%M:%S')))
q.join()
if __name__ == '__main__':
q = queue.Queue(maxsize=3)
# 3 threads to consume
threads_num = 3
for i in range(threads_num):
t = threading.Thread(name="consumerThread-" + str(i), target=consume, args=(q,))
t.start()
# thread to produce
t = threading.Thread(name="produceThread", target=producer, args=(q,))
t.start()
# q.join()
网友评论