进程 6.进程池中的Queue

2021/12/15 7:16:56

本文主要是介绍进程 6.进程池中的Queue,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

进程池中的Queue

实现进程池中的进程通信

import multiprocessing
import time

# 写入数据到queue
def write_queue(queue):
    for i in range(10):
        if queue.full():
            print('队列已满')
            break
        queue.put(i)
        print('已写入:',i)
        time.sleep(0.5)

# 从queue读取数据
def read_queue(queue):
    while True:
        if queue.empty():
            print('队列已空')
            break
        value = queue.get()
        print('已读取:',value)

if __name__ == '__main__':
    # 创建进程池
    pool = multiprocessing.Pool(3)

    # 创建进程池中的queue
    queue = multiprocessing.Manager().Queue(5)

    # 进程池中的进程执行操作queue的方法
    # 同步方式
    # pool.apply(write_queue,(queue,))
    # pool.apply(read_queue,(queue,))
    # 异步方式
    result = pool.apply_async(write_queue,(queue,))
    result.wait()
    pool.apply_async(read_queue,(queue,))
    pool.close()
    pool.join()
	
	
已写入: 0
已写入: 1
已写入: 2
已写入: 3
已写入: 4
队列已满
已读取: 0
已读取: 1
已读取: 2
已读取: 3
已读取: 4
队列已空


这篇关于进程 6.进程池中的Queue的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程