import multiprocessing
import time
def write_queue(queue):
# 循环向对列中写入数据
for i in range(10):
# 判断对列是否已满
if queue.full():
print("队列已满!")
break
# 对列中写入元素
queue.put(i)
print("写入成功, 已经写入", i)
#time.sleep(0.5)
def read_queue(queue):
while True:
# 判断对列是否为空
if queue.qsize() == 0:
print("队列已空!")
break
# 获取对列中的元素
value = queue.get()
print("已经读取:", value)
def main():
# 创建进程池
pool = multiprocessing.Pool(2)
# 创建进程池中的队列
queue = multiprocessing.Manager().Queue(5)
# 使用进程池执行任务
# # # 3.1 同步方式
# pool.apply(write_queue, (queue, ))
# pool.apply(read_queue, (queue, ))
# # 3.2 异步方式 pool.apply_async() 返回值 ApplyResult 对象,该对象由一个 wait() 的方法
result= pool.apply_async(write_queue, (queue, ))
result.wait()
pool.apply_async(read_queue, (queue, ))
pool.close() #表示不再接收新的任务
pool.join() # 表示主进程会等待进程池执行结束后推出
if __name__ == "__main__":
main()
进程池中的进程间的通信
最新推荐文章于 2022-07-05 10:59:03 发布