python-3.x - 如何在python3多处理中保持没有“主线程”的进程?
问题描述
python中的多处理启动了一个新进程。
在那个新进程中,我创建了 2 个新线程,并且在启动新进程的“主线程”中什么也不做,似乎该进程已经消失了。
例子:
new_process = multiprocessing.Process(target=new_proc_main, name=yyy)
new_process.start()
def new_proc_main():
thread1 = threading.Thread(target=xxxx, name=thread1)
thread1.start()
thread2 = threading.Thread(target=xxxx, name=thread2)
thread2.start()
如何在线程 1 和 2 运行时保持新进程处于活动状态?
解决方案
我写了一个测试程序。这是 MacOS 上的 Python 3.6.2
import multiprocessing
import time
def new_main():
import threading
my_thread = threading.Thread(target=dummy_main)
my_thread.start()
my_thread.join()
def dummy_main():
while True:
print("thread running")
time.sleep(1)
print("start process")
p = multiprocessing.Process(target=new_main)
p.start()
关键是我必须有my_thread.join()
。如果我没有,程序会立即退出。
推荐阅读
- api - 使用 POSTMAN 提交表单
- python - 无法在 anaconda 3 (python 3)、linux 中安装 pygame
- python - 如何在当前命令行目录中运行 Python 脚本?
- html - 是否可以使 popover 等于变量或函数?
- javascript - 试图让我的输出显示在正文部分,格式包括页眉、正文(带背景)和页脚
- html - 如何将图像幻灯片放在 div 框中?
- sql - PostgreSQL 慢速运行查询
- python - Why does `pip install` seem to change the interpreter line on some machines?
- javascript - Use custom SCSS with Bootstrap-Vue + Webpack + Vue.js
- excel - Reference a Sheet and Cell for use in Formula