Python进程间通信Queue实例解析
Python  /  管理员 发布于 7年前   152
本文研究的主要是Python进程间通信Queue的相关实例,具体如下。
1.Queue使用方法:
2.Queue使用实例:
来,上代码:
#!/usr/bin/env python3import timefrom multiprocessing import Process,Queueq = Queue() #创建列队,不传数字表示列队不限数量for i in range(11): q.put(i)def A(): while 1: try: num = q.get_nowait() print('我是进程A,取出数字:%d'%num) time.sleep(1) except : breakdef B(): while 1: try: num = q.get_nowait() print('我是进程B,取出数字:%d'%num) time.sleep(1) except : breakp1 = Process(target = A)p2 = Process(target = B)p1.start()p2.start()
此程序是在队列中加入10个数字,然后用2个进程来取出。
运行结果:
我是进程A,取出数字:0
我是进程B,取出数字:1
我是进程A,取出数字:2
我是进程B,取出数字:3
我是进程A,取出数字:4
我是进程B,取出数字:5
我是进程B,取出数字:6
我是进程A,取出数字:7
我是进程B,取出数字:8
我是进程A,取出数字:9
我是进程B,取出数字:10
3.使用进程池Pool时,Queue会出错,需要使用Manager.Queue:
上代码
#!/usr/bin/env python3import timefrom multiprocessing import Pool,Manager,Queueq = Manager().Queue()for i in range(11): q.put(i)def A(i): num = q.get_nowait() print('我是进程%d,取出数字:%d'%(i,num)) time.sleep(1) pool = Pool(3)for i in range(10): pool.apply_async(A,(i,))pool.close()pool.join()
运行结果:
我是进程1,取出数字:0
我是进程0,取出数字:1
我是进程2,取出数字:2
我是进程4,取出数字:3
我是进程3,取出数字:4
我是进程5,取出数字:5
我是进程6,取出数字:6
我是进程7,取出数字:7
我是进程8,取出数字:8
我是进程9,取出数字:9
当把Manager().Queue()直接换成Queue(),可能会出现资源混乱,缺少进程。
4.主进程定义了一个Queue类型的变量,并作为Process的args参数传给子进程processA和processB,两个进程一个向队列中写数据,一个读数据。
import timefrom multiprocessing import Process,QueueMSG_QUEUE = Queue(5)def startA(msgQueue): while True: if msgQueue.empty() > 0: print 'queue is empty %d' % (msgQueue.qsize()) else: msg = msgQueue.get() print 'get msg %s' % (msg,) time.sleep(1)def startB(msgQueue): while True: msgQueue.put('hello world') print 'put hello world queue size is %d' % (msgQueue.qsize(),) time.sleep(3)if __name__ == '__main__': processA = Process(target=startA,args=(MSG_QUEUE,)) processB = Process(target=startB,args=(MSG_QUEUE,)) processA.start() print 'processA start..' processB.start() print 'processB start..'
其打印的结果如下:
C:\Python27\python.exe E:/outofmemory/test/queuetest/queuetest.py
processA start..
processB start..
queue is empty 0
put hello world queue size is 1
get msg hello world
queue is empty 0
queue is empty 0
put hello world queue size is 1
get msg hello world
queue is empty 0
queue is empty 0
put hello world queue size is 1
总结
以上就是本文关于Python进程间通信Queue实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号