全局数组list_of_conditions已添加元素却为空的问题排查
问题分析与解决
问题根源
你的代码报错IndexError: pop from empty list,核心原因是Python多进程的内存隔离机制:
- 当用
multiprocessing.Process创建子进程时,子进程会复制父进程的所有内存数据(包括全局变量list_of_conditions),形成独立的副本。 - 父进程中
function_2往list_of_conditions里添加的Condition对象,只存在于父进程的列表副本中;子进程里的function_1操作的是另一个空的列表副本,自然执行pop()时会报错。
解决方案
方案1:直接传递Condition对象(推荐)
不需要依赖全局列表,直接把Condition对象作为参数传给子进程的函数,这是最简洁的实现方式:
import time from multiprocessing import Process, Condition def function_1(condition): time.sleep(1) # 缩短等待时间方便测试 with condition: condition.notify() print("F1: Done") def function_2(): condition = Condition() with condition: p1 = Process(target=function_1, args=(condition,), daemon=True) p1.start() condition.wait() print("Finished") if __name__ == "__main__": function_2()
方案2:使用多进程共享列表
如果必须用全局列表的形式,需要用multiprocessing.Manager创建跨进程共享的列表,确保所有进程操作的是同一个列表实例:
import time from multiprocessing import Process, Condition, Manager def function_1(list_of_conditions): time.sleep(1) condition = list_of_conditions.pop() with condition: condition.notify() print("F1: Done") def function_2(list_of_conditions): condition = Condition() list_of_conditions.append(condition) with condition: p1 = Process(target=function_1, args=(list_of_conditions,), daemon=True) p1.start() condition.wait() print("Finished") if __name__ == "__main__": with Manager() as manager: shared_list = manager.list() function_2(shared_list)
注意事项
- 多进程下不要依赖普通全局变量做数据共享,必须使用
multiprocessing提供的共享数据结构(比如Manager、Queue、Pipe等)。 - 使用Condition时,必须在
with语句块中调用wait()和notify(),确保锁的正确获取与释放。
内容的提问来源于stack exchange,提问作者Tricker Macedonia
相关产品推荐
相关产品推荐

