并发编程时守护进程在pycharm与python shell中的运行结果不同

原代码如下

 1 from multiprocessing import Process
 2 import time
 3 import random
 4 
 5 
 6 def task(name):
 7     print('%s is running' % name)
 8     time.sleep(random.randint(2, 3))
 9     print('%s is finished' % name)
10 
11 
12 if __name__ == '__main__':
13     p = Process(target=task, args=('Subprocess',))
14     p.daemon = True    # 子进程设置为守护进程
15     p.start()
16 
17     print('Parent process is finished')

Python shell运行结果

1 Parent process is finished

PyCharm运行结果

1 Parent process is finished
2 Subprocess is running
3 Subprocess is finished

结果分析

在原代码14行处,把子进程设置成了守护进程,守护进程会在主进程代码结束后就终止,显然Python shell的运行结果是对的

解决方法

pycharm工具栏---->run---->Edit Configurations,Execution---->run with python console得到的是错误结果,Execution---->Emulate terminal in output console或者Execution下面都不选择得到的是正确的结果。如下图所示:

猜你喜欢

转载自www.cnblogs.com/miaoning/p/10879054.html
今日推荐