首页 > 编程语言 > 详细

python Queue模块用于多线程通信

时间:2015-08-14 19:32:36      阅读:293      评论:0      收藏:0      [点我收藏+]
# -*-coding:utf-8 -*-
import Queue
import threading
import time
q = Queue.Queue(100000)


def producer():
    for i in range(1000):
        q.put(i)
        time.sleep(0)


def consumer():
    for i in range(1000):
        print q.get(), q.qsize()
        time.sleep(0)

threads = []

th = threading.Thread(target=consumer)
rh = threading.Thread(target=producer)
threads.append(rh)
threads.append(th)

for t in threads:
    t.start()

Queue模块包括Queue队列,可用于多线程的通信,上面的代码是消费者和生产者的示例程序。

需要注意的是,当消费者线程,读取Queue时Queue.get()若Queue为空获取不到内容,线程会阻塞在这里,直到成功获取内容。

本文出自 “magicpwn” 博客,请务必保留此出处http://magicpwn.blog.51cto.com/10497784/1684630

python Queue模块用于多线程通信

原文:http://magicpwn.blog.51cto.com/10497784/1684630

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!