![](/img/trans.png)
[英]Getter on a object inheriting from multiprocessing.Process
[英]How to prevent multiprocessing from inheriting imports and globals?
我在更大的代码库中使用多处理,其中一些导入语句有副作用。 如何在后台进程中运行 function 而不让它继承全局导入?
# helper.py:
print('This message should only print once!')
# main.py:
import multiprocessing as mp
import helper # This prints the message.
def worker():
pass # Unfortunately this also prints the message again.
if __name__ == '__main__':
mp.set_start_method('spawn')
process = mp.Process(target=worker)
process.start()
process.join()
背景:导入 TensorFlow 初始化 CUDA 保留一定数量的 GPU ZCD69B4957F06CD818D7BF3D6198。 因此,产生过多进程会导致 CUDA OOM 错误,即使这些进程不使用 TensorFlow。
没有答案的类似问题:
# helper.py:
print('This message should only print once!')
# main.py:
import multiprocessing as mp
def worker():
pass
def main():
# Importing the module only locally so that the background
# worker won't import it again.
import helper
mp.set_start_method('spawn')
process = mp.Process(target=worker)
process.start()
process.join()
if __name__ == '__main__':
main()
是否有资源可以准确解释多处理模块在启动
mp.Process
时的作用?
超级快速版本(使用生成上下文而不是分叉)
准备好一些东西(一对用于通信、清理回调等的管道),然后使用fork()
exec()
创建一个新进程。 在 windows 它是Create
ProcessW()
。 新的 python 解释器使用启动脚本spawn_main())
调用,并通过精心设计的命令字符串和-c
开关传递 pipe 文件描述符通信。 启动脚本稍微清理环境,然后从其通信 pipe 中取消Process
object。 最后调用进程object的run
方法。
那么模块的导入呢?
Pickle 语义处理其中的一些,但__main__
和sys.modules
需要一些 tlc, 在此处处理(在“清理环境”位期间)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.