![](/img/trans.png)
[英]Python multiprocessing - AssertionError: can only join a child process
[英]Python Multiprocessing: The child process finished but did not join
我尝试实现一个多处理代码来生成一些感兴趣的字典。
这是我的逻辑:
from multiprocessing import Manager, Queue, Process
input_list = Queue()
for x in my_input: # my_input is my input data
input_list.put(x)
output = Manager().dict()
def job():
while input_list.qsize()>0:
x = input_list.get()
result = my_func(x) # Do something here
output[x] = result
def monitor():
while True:
if input_list.qsize() > 0:
time.sleep(1)
print("Item List is Empty")
print("Does all the result being save?", len(output.keys()) == len(my_input))
job_list = [Process(target=monitor)]
for _ in range(num_of_worker):
job_list.append(Process(target=job))
for j in job_list:
j.start()
for j in job_list:
j.join()
print("The script is finished")
我的代码逻辑很简单。
job
(做某事并将其保存到字典)和monitor
(打印队列中的所有内容时打印并打印保存了多少结果)。start
并join
。output 我得到:
Item List is Empty
Does all the result being save? True
...
一些子进程没有完成,还没有加入。 脚本卡在这里,没有打印“脚本完成”。
尽管监视器告诉我一切都已完成(通过检查 input_list 中剩余的项目数和input_list
中存储的结果output
),但我的脚本将卡在join
语句中。
而且,这个错误是不可复制的。 如果我看到我的脚本卡住超过 5 分钟,我将手动终止它并重新启动它。 我发现脚本可以正常完成(比如 10 次中有 3 次)。
会发生什么?
备注:由于我怀疑错误是某些子进程没有加入,所以我尝试了Event
。 当监视器发现input_list
为空且output
完全填满时,会杀掉所有进程。 但是脚本也停留在事件触发上。 (和上面一样,代码不会每次都卡住,它可以工作 10 次中的 3 次)。
@Homer512 评论让我了解代码中的错误在哪里。
从切换
def job():
while input_list.qsize>0:
x = input_list.get()
...
至
def job():
while input_list.qsize>0:
try:
x = input_list.get(True,5)
...
except Empty:
return 0
我的脚本停留在 join 的原因是当input_list
只剩下 1 个元素时,它会触发job
的 while 语句,但只有一个进程可以从队列中获取一些东西。 另一个进程将在没有适当超时的情况下停留在get
上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.