[英]Why can't execute multiprocess using member variables of class?
I tested a code using python 3.6 and python 3.7 by 2 cases.我使用 python 3.6 和 python 3.7 测试了 2 个案例的代码。
1 case) using Member variables of class 1例)使用class的成员变量
import multiprocessing as mp
import sys
class Foo:
def do_multiprocessing(self):
ctx = mp.get_context('spawn')
self.process_1 = ctx.Process(target=self.do_stuff1)
self.process_2 = ctx.Process(target=self.do_stuff2)
self.process_1.start()
self.process_2.start()
def do_stuff1(self):
print("Doing 1")
def do_stuff2(self):
print("Doing 2")
if __name__ == "__main__":
print("PYTHON VERSION : ", sys.version)
foo = Foo()
foo.do_multiprocessing()
Result: When i executed it using python 3.6, working well.结果:当我使用 python 3.6 执行它时,运行良好。 However, when i executed it using python 3.7, a error occurred.(TypeError: Can't pickle weakref object)
但是,当我使用 python 3.7 执行它时,发生了错误。(TypeError: Can't pickle weakref object)
2 case) using local variables 2 case) 使用局部变量
import multiprocessing as mp
import sys
class Foo:
def do_multiprocessing(self):
ctx = mp.get_context('spawn')
process_1 = ctx.Process(target=self.do_stuff1)
process_2 = ctx.Process(target=self.do_stuff2)
process_1.start()
process_2.start()
def do_stuff1(self):
print("Doing 1")
def do_stuff2(self):
print("Doing 2")
if __name__ == "__main__":
print("PYTHON VERSION : ", sys.version)
foo = Foo()
foo.do_multiprocessing()
Result: When i executed it using python 3.6 and python 3.7, working well.结果:当我使用 python 3.6 和 python 3.7 执行它时,运行良好。
Why can't execute multiprocess using member variables of class?为什么不能使用 class 的成员变量执行多进程? And why can execute multiprocess using local variables?
为什么可以使用局部变量执行多进程?
I can't understand why a code execute.我不明白为什么要执行代码。
ps) if using mp.get_context('fork'), the code works well using python 3.6 and python 3.7 on case 1. ps) 如果使用 mp.get_context('fork'),则代码在案例 1 中使用 python 3.6 和 python 3.7 运行良好。
By passing self.do_stuff2
to process_2
, you're trying to give that process access to the entirety of self
(as an implicit argument), which includes self.process_1
.通过将
self.do_stuff2
传递给process_2
,您试图让该进程访问整个self
(作为隐式参数),其中包括self.process_1
。 You can see how giving one child process meaningful access to another might be complicated (unless you have the OS replicate the whole (parent) process with 'fork'
).您可以看到让一个子进程对另一个子进程进行有意义的访问可能很复杂(除非您让操作系统使用
'fork'
复制整个(父)进程)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.