[英]early exit from multiprocessing.Pool.map (raise in child process doesn't work)
[英]multiprocessing in threads in python doesn't make every child process work
在python中使用threading
模块在每个线程中执行子进程时,某些进程无法正常启动和挂起,如示例代码的输出。
由于python中的IPC,启动进程似乎需要排他控制。 这样对吗?
使用线程锁定,它可以完美工作。 我只想创建一个线程来控制子进程的生死管理。
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
import multiprocessing
import threading
import fire
from logzero import logger
def process_method():
logger.info("process log")
def start_process():
logger.info("starting thread")
process = multiprocessing.Process(target=process_method)
process.daemon = True
process.start()
process.join()
def main(num_of_threads=3):
threads = []
for _ in range(num_of_threads):
t = threading.Thread(target=start_process)
t.daemon = True
t.start()
threads.append(t)
for t in threads:
t.join()
logger.info("program done")
if __name__ == "__main__":
fire.Fire(main)
$ python '/tmp/tmp.lY3YDIltYg/test.py' 30
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:16] process log
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:20] starting thread
[I 190822 09:10:38 test:16] process log
[I 190822 09:10:38 test:16] process log
[I 190822 09:10:38 test:16] process log
[I 190822 09:10:38 test:16] process log
[I 190822 09:10:38 test:16] process log
我假设您使用的是类似UNIX的系统? 因为如果是这样,那么您在这里做的不好。 将fork
与线程混合是个坏主意 ,Python在类UNIX系统上的默认Process
实现使用fork
,因此,通过在线程中启动Process
es,就可以从多线程进程中进行fork
。
这里有两种解决方案:
daemon
,因此当主进程的主线程完成时,它们将被毫不客气地杀死)。 'spawn'
方法将代码移植到Windows),但要花一些时间来简化Process
创建在类似UNIX的系统上),因此从主进程执行的唯一fork
是在启动任何线程之前完成的,所有以后的fork
操作都是从(无线程)派生服务器完成的。 您要做的就是在if __name__ == "__main__":
保护之后的第一行添加multiprocessing.set_start_method('forkserver')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.