python:threading多线程模块-使用Queue模块保持线程同步
2013-07-27 19:57
696 查看
利用Queue对象先进先出的特性,将每个生产者的数据一次存入队列,而每个消费者将依次从队列中取出数据
本文出自 “师父领进门,修行靠个人!” 博客,请务必保留此出处http://zeping.blog.51cto.com/6140112/1258979
import threading # 导入threading模块 import Queue # 导入Queue模块 class Producer(threading.Thread):# 定义生产者类 def __init__(self,threadname): threading.Thread.__init__(self,name = threadname) def run(self): global queue # 声明queue为全局变量 queue.put(self.getName()) # 调用put方法将线程名添加到队列中 print self.getName(),'put ',self.getName(),' to queue' class Consumer(threading.Thread):# 定义消费者类 def __init__(self,threadname): threading.Thread.__init__(self,name = threadname) def run(self): global queue print self.getName(),'get ',queue.get(),'from queue'#调用get方法获取队列中内容 queue = Queue.Queue() # 生成队列对象 plist = [] # 生成者对象列表 clist = [] # 消费者对象列表 for i in range(10): p = Producer('Producer' + str(i)) plist.append(p) # 添加到生产者对象列表 for i in range(10): c = Consumer('Consumer' + str(i)) clist.append(c) # 添加到消费者对象列表 for i in plist: i.start() # 运行生产者线程 i.join() for i in clist: i.start() # 运行消费者线程 i.join() ######运行结果###### >>> Producer0 put Producer0 to queue Producer1 put Producer1 to queue Producer2 put Producer2 to queue Producer3 put Producer3 to queue Producer4 put Producer4 to queue Producer5 put Producer5 to queue Producer6 put Producer6 to queue Producer7 put Producer7 to queue Producer8 put Producer8 to queue Producer9 put Producer9 to queue Consumer0 get Producer0 from queue Consumer1 get Producer1 from queue Consumer2 get Producer2 from queue Consumer3 get Producer3 from queue Consumer4 get Producer4 from queue Consumer5 get Producer5 from queue Consumer6 get Producer6 from queue Consumer7 get Producer7 from queue Consumer8 get Producer8 from queue Consumer9 get Producer9 from queue
本文出自 “师父领进门,修行靠个人!” 博客,请务必保留此出处http://zeping.blog.51cto.com/6140112/1258979
相关文章推荐
- Python多线程编程使用Queue模块保持线程同步
- python threading模块使用 以及python多线程操作的实践(使用Queue队列模块)
- python多线程(2)--thread和threading模块的使用
- 使用Python之paramiko模块和threading实现多线程登录多台Linux服务器
- Python:使用threading模块实现多线程
- python模块之threading: 在python中使用多线程
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程(转)
- python模块之threading: 在python中使用多线程
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程编程一[综述]
- Python:使用threading模块实现多线程(转)
- Python:使用threading模块实现多线程(转)
- [Python module]使用threading模块实现多线程编程一[综述]
- python多线程模块:threading使用方法(参数传递)
- Python:使用threading模块实现多线程
- python学习笔记之使用threading模块实现多线程(转)
- python多线程模块:threading使用方法
- Python:使用threading模块实现多线程(转)