Python进程间通信Queue实例解析

yipeiwu_com5年前Python基础

本文研究的主要是Python进程间通信Queue的相关实例,具体如下。

1.Queue使用方法:

  • Queue.qsize():返回当前队列包含的消息数量;
  • Queue.empty():如果队列为空,返回True,反之False ;
  • Queue.full():如果队列满了,返回True,反之False;
  • Queue.get():获取队列中的一条消息,然后将其从列队中移除,可传参超时时长。
  • Queue.get_nowait():相当Queue.get(False),取不到值时触发异常:Empty;
  • Queue.put():将一个值添加进数列,可传参超时时长。
  • Queue.put_nowait():相当于Queue.get(False),当队列满了时报错:Full。

2.Queue使用实例:

来,上代码:

#!/usr/bin/env python3

import time
from multiprocessing import Process,Queue

q = 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 :
      break

def B():
  while 1:
    try:
      num = q.get_nowait()
      print('我是进程B,取出数字:%d'%num)
      time.sleep(1)
    except :
      break

p1 = 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 python3

import time
from multiprocessing import Pool,Manager,Queue

q = 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 time
from multiprocessing import Process,Queue

MSG_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实例解析的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

1分钟快速生成用于网页内容提取的xslt

1分钟快速生成用于网页内容提取的xslt

1分钟快速生成用于网页内容提取的xslt,具体内容如下 1、项目背景 在《Python即时网络爬虫项目说明》一文我们说过要做一个通用的网络爬虫,而且能节省程序员大半的时间,而焦点问题就是...

Python设计模式之代理模式实例详解

Python设计模式之代理模式实例详解

本文实例讲述了Python设计模式之代理模式。分享给大家供大家参考,具体如下: 代理模式(Proxy Pattern):为其他对象提供一种代理以控制对这个对象的访问 #!/usr/b...

Python Web框架Flask信号机制(signals)介绍

信号(signals) Flask信号(signals, or event hooking)允许特定的发送端通知订阅者发生了什么(既然知道发生了什么,那我们可以知道接下来该做什么了)。...

selenium+python自动化测试环境搭建步骤

selenium+python自动化测试环境搭建步骤

相对于自动化测试工具QTP来说,selenium小巧、免费,而且兼容Google、FireFox、IE多种浏览器,越来越多的人开始使用selenium进行自动化测试。 我是使用的pyth...

python socket网络编程步骤详解(socket套接字使用)

一、套接字套接字是为特定网络协议(例如TCP/IP,ICMP/IP,UDP/IP等)套件对上的网络应用程序提供者提供当前可移植标准的对象。它们允许程序接受并进行连接,如发送和接受数据。为...