创建mytest.py,代码如下:
from multiprocessing import Process
import mytest
class testProcess(Process):
def __init__(self):
Process.__init__(self)
self.a = 20
def run(self):
self.a = 1000
print('In class: a is %d' % self.a)
if __name__ == '__main__':
p = mytest.testProcess()
p.start()
p.join()
print('In main: a = %d' % p.a)
在输出结果中,先后输出1000、20,第二个输出结果为什么不是1000?但如果使用多线程,将Process换成threading.Thread,则两个输出结果都是1000、1000,符合我的预期。还是基于Process,如何小幅修改上述代码,使得进程运行后能返回被修改后的a的值?
这个是因为进程是复制当前对象在新进程内运行,类似于按值传参,如果打印下两者id就能发现并非同一对象(print(id(self)), print(id(p)))。若要进行进程间通信(IPC),可考虑构建一容器(比如multiprocessing.Queue),在分支进程调用Queue.put向其中存入需返回的值,然后在主进程调用Queue.get获取