![](/img/trans.png)
[英]Passing a function that accepts class member functions as variables into python multiprocess pool.map()
[英]Why can't execute multiprocess using member variables of class?
我使用 python 3.6 和 python 3.7 測試了 2 個案例的代碼。
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()
結果:當我使用 python 3.6 執行它時,運行良好。 但是,當我使用 python 3.7 執行它時,發生了錯誤。(TypeError: Can't pickle weakref object)
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()
結果:當我使用 python 3.6 和 python 3.7 執行它時,運行良好。
為什么不能使用 class 的成員變量執行多進程? 為什么可以使用局部變量執行多進程?
我不明白為什么要執行代碼。
ps) 如果使用 mp.get_context('fork'),則代碼在案例 1 中使用 python 3.6 和 python 3.7 運行良好。
通過將self.do_stuff2
傳遞給process_2
,您試圖讓該進程訪問整個self
(作為隱式參數),其中包括self.process_1
。 您可以看到讓一個子進程對另一個子進程進行有意義的訪問可能很復雜(除非您讓操作系統使用'fork'
復制整個(父)進程)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.