码迷,mamicode.com
首页 > 编程语言 > 详细

python Queue模块用于多线程通信

时间:2015-08-14 19:34:35      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:python queue   多线程   

# -*-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模块用于多线程通信

标签:python queue   多线程   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!