python multiprocessing使用踩坑记录随笔

python因为有GIL(Global Interpreter Lock)锁的问题,所以在计算密集型程序中,推荐使用multiprocessing多进程编程。

在使用multiprocessing创建子进程时,很容易遇到一个不易发现的坑,这里记录一下。

 1 import multiprocessing
 2 import time
 3 import threading
 4 import os
 5 
 6 
 7 def fun():
 8 
 9     print("in new process, pid = {}, ppid={}".format(os.getpid(), os.getppid()))
10     print("in new thread, id = %s" % threading.current_thread().ident)
11 
12     time.sleep(3)
13     print("process {} finish.".format(os.getpid()))
14 
15 
16 def main():
17     print("main pid = {}, ppid={}".format(os.getpid(), os.getppid()))
18     p = multiprocessing.Process(target=fun())
19     print("-----1")
20     p.start()
21     print("-----2")
22     p.join()
23     print("-----3")
24 
25 
26 if __name__ == '__main__':
27     main()

执行结果显示如下:

1 main pid = 114664, ppid=111764
2 in new process, pid = 114664, ppid=111764
3 in new thread, id = 106604
4 process 114664 finish.
5 -----1
6 -----2
7 -----3

发现,创建子进程并没有成功。fun()函数是串行的在主进程中运行的。

原因就出在fun后面的()号上。正确的使用方法,fun后面不能添加括号。

p = multiprocessing.Process(target=fun)

修改之后,程序执行结果如下:

main pid = 119200, ppid=109900
-----1
-----2
in new process, pid = 118472, ppid=119200
in new thread, id = 119512
process 118472 finish.
-----3

从结果可以看出,子进程创建成功,子进程和主进程并行执行。主进程等待子进程退出后再退出。

这个确实是一个容易被忽略的坑,不明白python为什么会让前者顺利执行,而不是选择报语法错误。

posted @ 2022-11-30 11:41  慕流  阅读(139)  评论(0编辑  收藏  举报