【发布时间】:2022-01-04 13:58:53
【问题描述】:
我是多处理和多线程的新手。出于学习目的,我正在尝试使用队列实现 IPC。
代码
from multiprocessing import Process, Queue, Lock
import math
def calculate_square(sq_q, sqrt_q):
itm = sq_q.get()
print(f"Calculating sq of: {itm}")
square = itm * itm
sqrt_q.put(square)
def calculate_sqroot(sqrt_q, result_q):
itm = sqrt_q.get()
print(f"Calculating sqrt of: {itm}")
sqrt = math.sqrt(itm)
result_q.put(sqrt)
sq_q = Queue()
sqrt_q = Queue()
result_q = Queue()
for i in range(5, 20):
sq_q.put(i)
p_sq = Process(target=calculate_square, args=(sq_q, sqrt_q))
p_sqrt = Process(target=calculate_sqroot, args=(sqrt_q, result_q))
p_sq.start()
p_sqrt.start()
p_sq.join()
p_sqrt.join()
while not result_q.empty():
print(result_q.get())
说明
这里我试图用两个不同的过程运行两个函数,每个过程计算数字的平方并再次计算数字的平方根。
队列
- sq_q:
Queue containing the initial number whose square root is to calculated. - sqrt_q:
Queue containing the numbers whose square root has to be calculated - result_q:
Queue containing final result.
问题
仅消耗
sq_q的第一项。
输出:
5.0
我希望输出是:
[5, 6, 7, 8, .. , 19]
请注意,这纯粹是为了学习目的,我想用多个队列实现 IPC,尽管它可以通过共享对象锁和数组来实现。
【问题讨论】:
标签: python queue ipc multiprocess