我尝试运行以下多处理代码:
import multiprocessing
class test(multiprocessing.Process):
def __init__(self, name):
multiprocessing.Process.__init__(self)
self.name = name
self.finished = False
def run(self):
print("executed")
self.finished = True
test_list = []
test_list.append(test('first'))
test_list.append(test('second'))
for t in test_list:
t.start()
for t in test_list:
t.join()
for t in test_list:
print(t.finished)
并获得结果:
executed
executed
False
False
False
输出似乎很奇怪。我已在方法finished
中将属性True
设置为run
,输出executed
表示已执行run
方法。而且,如果我在方法print(self.finished)
中的self.finished=True
之后立即添加一行run
,则输出将为True
。为什么在多处理完成后类属性finished
会发生变化?
谢谢!
答案 0 :(得分:1)
self.finished = True
在另一个进程中执行,只更改该进程中的变量,但是您正在从主进程中打印该值。您需要共享的变量。
from multiprocessing import Process,Value
from ctypes import c_bool
class test(Process):
def __init__(self,name):
super().__init__()
self.name = name
self._finished = Value(c_bool,False)
def run(self):
print(self.name,'executed')
self._finished.value = True
@property
def finished(self):
return self._finished.value
if __name__ == '__main__':
test_list = [test('first'),
test('second')]
for t in test_list:
t.start()
for t in test_list:
t.join()
for t in test_list:
print(t.finished)
答案 1 :(得分:0)
这将允许您在进程之间共享已完成的值。它使用multiprocessing.Value
使用共享内存创建共享对象。
from multiprocessing import Process, Value
class test(Process):
def __init__(self, name, fin):
Process.__init__(self)
self.name = name
self.finished = fin
def run(self):
print("executed")
self.finished.value = True
test_list = []
test_list.append(test('first', Value('b', False)))
test_list.append(test('second', Value('b', False)))
for t in test_list:
t.start()
for t in test_list:
t.join()
for t in test_list:
print(bool(t.finished.value))