进程 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
队列已空
上一篇:html视频播放器的代码 及其参数详解


下一篇:C++优先队列priority_queue详解