Skip to main content
 首页 » 编程设计

python之多处理不保留结果

2025年01月19日16lovecherry

我尝试运行以下多处理代码:

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多处理完成后更改?

谢谢!

请您参考如下方法:

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)