multiprocessing跨平台锁的使用(Windows问题)

Posted 踏雪无痕何处是

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了multiprocessing跨平台锁的使用(Windows问题)相关的知识,希望对你有一定的参考价值。

在Windows上可能遇到,开启的子进程不会关闭的问题

 

参考multiprocessing官方文档:

Explicitly pass resources to child processes

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.

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 instance

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 as

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()

以上是关于multiprocessing跨平台锁的使用(Windows问题)的主要内容,如果未能解决你的问题,请参考以下文章

multiprocessing

multiprocessing

Python 多进程编程之multiprocessing--Process

Python进程之multiprocessing模块

multiprocessing总结

进程的创建-multiprocessing