multiprocessing跨平臺鎖的使用(Windows問題)

在Windows上可能遇到,開啓的子進程不會關閉的問題python

 

參考multiprocessing官方文檔:this

Explicitly pass resources to child processesspa

On Unix a child process can make use of a shared resource created in a parent process using a global resource. However, it is better to pass the object as an argument to the constructor for the child process.code

Apart from making the code (potentially) compatible with Windows this also ensures that as long as the child process is still alive the object will not be garbage collected in the parent process. This might be important if some resource is freed when the object is garbage collected in the parent process.進程

So for instanceip

from multiprocessing import Process, Lock def f(): ... do something using "lock" ... if __name__ == '__main__': lock = Lock() for i in range(10): Process(target=f).start() 

should be rewritten asci

from multiprocessing import Process, Lock def f(l): ... do something using "l" ... if __name__ == '__main__': lock = Lock() for i in range(10): Process(target=f, args=(lock,)).start()
相關文章
相關標籤/搜索