惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - Franky
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志
宝玉的分享
宝玉的分享
量子位
N
Netflix TechBlog - Medium
M
MIT News - Artificial intelligence
GbyAI
GbyAI
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tailwind CSS Blog
Y
Y Combinator Blog
L
LangChain Blog
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
U
Unit 42
Martin Fowler
Martin Fowler
aimingoo的专栏
aimingoo的专栏
G
Google Developers Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
月光博客
月光博客

老董笔记

尚硅谷机构在哪?尚硅谷培训怎么样?靠谱吗-互联网IT百科 韩顺平介绍,传智讲师,开办泰牛,入尚硅谷等一系列-互联网IT百科 pandas多重索引标准样式(写入excel有空行)-互联网IT百科 cannot join with no overlapping index names-互联网IT百科 pandas多列变多行(即宽表变长表)melt和stack函数-互联网IT百科 pandas多行转多列(长表变宽表)pivot和unstack-互联网IT百科 Index contains duplicate entries, cannot reshape完美解决-互联网IT百科 single positional indexer is out-of-bounds-互联网IT百科 Can only compare identically-labeled Series objects-互联网IT百科 pandas transform用法详解(多个案例)-互联网IT百科 python四舍五入精确实现-互联网IT百科 pandas的groupby使用apply分组排序-互联网IT百科 index 0 is out of bounds for axis 0 with size 0-互联网IT百科 pandas分组过滤filter函数-互联网IT百科 联想Win10系统如何禁用触摸屏关闭触摸-互联网IT百科 groupby分组计算transform转换返回相同长度序列-互联网IT百科 brooks seo教程python教程,brooks seo教程网盘,布鲁seo资源-互联网IT百科 电脑右键文件夹一直转圈电卡死怎么回事-互联网IT百科 施琪嘉的心理成长课(荐)-互联网IT百科 百度SEO公司_SEO推广公司哪家好_SEO外包服务如何选-老董笔记 groupby后agg同1列用多个聚合函数、不同列用不同函数、自定义函数-互联网IT百科 pandas的groupby单列多列分组聚合运算-互联网IT百科 DataFrameGroupBy对象及分组个数、分组大小、组名索引、组数据详解-互联网IT百科 pandas中groupby之Grouper and axis must be same length-互联网IT百科 pandas中groupby的分组原理-互联网IT百科 pandas的groupby的使用详解大全-互联网IT百科 openpyxl单元格自动换行强制换行Alignment(wrapText=True)-互联网IT百科 python教程全套(可就业)-互联网IT百科 联想win10系统CPU显示100%,电脑呼呼响怎么回事-互联网IT百科 如何自制CPU,CPU原理是怎么样的?-互联网IT百科
进程间的通信Queue队列-互联网IT百科
2019-06-06 · via 老董笔记

  进程(Process)之间的内存单元是独立的,A进程的变量不能被B进程使用。大家都在内存里有时候彼此之间需要通信,操作系统提供了很多机制来实现进程间的通信,今天学习Queue队列通信。

  一、Queue的认识

  multiprocessing模块的Queue可以实现多进程之间的数据传递,Queue本身是一个消息列队程序,首先用一个小实例来演示一下Queue用法:

# ‐*‐ coding: utf‐8 ‐*‐

from multiprocessing import Queue

q=Queue(3) # 初始化一个Queue对象,最多可接收三条put消息
q.put("消息1")
q.put("消息2")
print(q.full())  # False
q.put("消息3")
print(q.full()) # True

# 因为消息列队已满下面的try都会抛出异常,第一个try会等待2秒后再抛出异常,第二个Try会立刻抛出异常

try:
    q.put("消息4",True,2)
except Exception as e:
    print("抛出异常")
else:
    print("消息列队已满,现有消息数量:%s"%q.qsize())

try:
    q.put_nowait("消息4")
except Exception as e:
    print("抛出异常")
else:
    print("消息列队已满,现有消息数量:%s"%q.qsize())

# 判断消息列队是否已满,再写入
if not q.full():
    q.put_nowait("消息4")

# 判断消息列队是否为空,再读取
if not q.empty():
    for i in range(q.qsize()):
        print(q.get_nowait())
D:installpython3python.exe D:/pyscript/test/test.py
False
True
抛出异常
抛出异常
消息1
消息2
消息3

Process finished with exit code 0

  Queue相关说明

  初始化Queue()对象时(例如:q=Queue()),若括号中没有指定最大可接收的消息数量,或数量为负值,那么就代表可接受的消息数量没有上限(直到内存的尽头);

  Queue.qsize():返回当前队列包含的消息数量;

  Queue.empty():如果队列为空,返回True,反之False;

  Queue.full():如果队列满了,返回True,反之False;

  Queue.get([block[,timeout]]):获取队列中的一条消息,然后将其从列队中移除,block默认值为True;

  1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果为空,此时程序将被阻塞(停在读取状态),直到从消息列队读到消息为止,如果设置了timeout,则会等待timeout秒,若还没读取到任何消息,则抛出"Queue.Empty"异常;

  2)如果block值为False,消息列队如果为空,则会立刻抛出"Queue.Empty"异常;

  Queue.get_nowait():相当Queue.get(False);

  Queue.put(item,[block[,timeout]]):将item消息写入队列,block默认值为True;

  1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果已经没有空间可写入,此时程序将被阻塞(停在写入状态),直到从消息列队腾出空间为止,如果设置了timeout,则会等待timeout秒,若还没空间,则抛出"Queue.Full"异常;

  2)如果block值为False,消息列队如果没有空间可写入,则会立刻抛出"Queue.Full"异常;

  Queue.put_nowait(item):相当Queue.put(item,False);

  二、Queue实例通信

  利用Queue实例实现通信,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:

# ‐*‐ coding: utf‐8 ‐*‐

from multiprocessing import Process, Queue
import time, random


# 写数据进程执行的代码:
def write(q):
    for value in ['1', '2', '3']:
        print('Put %s in queue...' % value)
        q.put(value)
        time.sleep(random.random())


# 读数据进程执行的代码:
def read(q):
    while True:
        if not q.empty():
            value = q.get(True)
            print('Get %s from queue.' % value)
            time.sleep(random.random())
        else:
            break


if __name__ == "__main__":

    # 父进程创建Queue,并传给各个子进程:
    q = Queue()
    p_write = Process(target=write, args=(q,))
    p_read = Process(target=read, args=(q,))
    # 启动子进程写入:
    p_write.start()
    p_write.join()
    """
    用q这个队列作为中间人来交换两个进程的数据。
    """
    # 启动子进程读取:
    p_read.start()
    p_read.join()
    # p_read 进程里是死循环,无法等待其结束,只能强行终止:
    print('所有数据都写入并且读完,感谢队列q')

D:installpython3python.exe D:/pyscript/test/test.py
Put 1 in queue...
Put 2 in queue...
Put 3 in queue...
Get 1 from queue.
Get 2 from queue.
Get 3 from queue.
所有数据都写入并且读完,感谢队列q

Process finished with exit code 0

  三、进程池中使用Queue

  如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue(),而不是multiprocessing.Queue(),否则会得到一条如下的错误信息:

RuntimeError: Queue objects should only be shared between processes through inheritance

# ‐*‐ coding: utf‐8 ‐*‐

# 用Manager中的Queue
from multiprocessing import Manager,Pool
import os,time,random


def write(q):
    print("write(%s)子进程启动,父进程为(%s)" % (os.getpid(),os.getppid()))
    for i in [1,2,3]:
        time.sleep(random.random())
        q.put(i)


def read(q):
    print("read(%s)子进程启动,父进程为(%s)" % (os.getpid(),os.getppid()))
    for i in range(q.qsize()):
        time.sleep(random.random())
        print("read从Queue获取到消息:%s" % q.get(True))


if __name__ == "__main__":

    # 使用Manager中的Queue来初始化
    q = Manager().Queue()
    po = Pool()
    # 使用阻塞模式创建进程,writer完全执行完成后,再用read去读取.
    po.apply(write, (q,))
    po.apply(read, (q,))
    po.close()
    po.join()

D:installpython3python.exe D:/pyscript/test/test.py
write(12216)子进程启动,父进程为(10556)
read(11712)子进程启动,父进程为(10556)
read从Queue获取到消息:1
read从Queue获取到消息:2
read从Queue获取到消息:3

Process finished with exit code 0

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会