理解 Python 并发编程中的 join 方法

版权声明:本文为博主原创文章,可以转载,但转载前请联系博主。 https://blog.csdn.net/qq_33528613/article/details/84592608

代码清单 - 1:

from multiprocessing import Process
from time import ctime, sleep

def clock(interval):
        while True:
                print("The time is %s" % ctime())
                sleep(interval)

if __name__ == "__main__":
        p = Process(target=clock, args=(2,))
	p.daemon = False
        p.start()

        print("Done!")

输出:

$ python3 p337_single_process_with_function.py
Done!
The time is Wed Nov 28 18:57:49 2018
The time is Wed Nov 28 18:57:51 2018
The time is Wed Nov 28 18:57:53 2018
The time is Wed Nov 28 18:57:55 2018
# 永远执行。。

解释:
子进程 p 是非后台进程(p.daemon = False),
虽然主进程终止了(从打印出 Done! 可以看出),但子进程不会随主进程终止而终止;
并且,子进程装载的函数 clock 是死循环,因此永远执行。

代码清单 - 2:

from multiprocessing import Process
from time import ctime, sleep

def clock(interval):
        while True:
                print("The time is %s" % ctime())
                sleep(interval)

if __name__ == "__main__":
        p = Process(target=clock, args=(2,))
        p.daemon = False
        p.start()
        p.join()
        print("Done!")

代码清单 - 3:

from multiprocessing import Process
from time import ctime, sleep

def clock(interval):
        while True:
                print("The time is %s" % ctime())
                sleep(interval)

if __name__ == "__main__":
        p = Process(target=clock, args=(2,))
        p.daemon = True
        p.start()
        p.join()
        print("Done!")

代码清单2、3的输出均为:

# 没有打印出 Done!
The time is Wed Nov 28 19:14:03 2018
The time is Wed Nov 28 19:14:05 2018
# 永远执行。。。

注意:

  1. 代码2比代码1多了 p.join() ;
  2. 代码3与代码2相比,p.daemon = True

解释:

  1. 先来看看代码3,进程 p 为后台进程,如果主进程结束了,则应该会打印出 Done!
    但是,代码 3 没有打印出 Done! ,说明主进程没有结束。
    为什么主进程没有结束呢?
    这是因为 p.join() ,主进程在等待子进程 p 终止。
    而子进程 p 中装入的函数 clock 是死循环,子进程永远不会结束;
    (按照我的理解)所以主进程也永远不会结束,主进程的代码“卡在” p.join() 这里,没有继续往下执行。
  2. 再来看看代码 2 ,由于 p.daemon = False ,子进程 p 为非后台进程,子进程 p 并不会随主进程终止而终止。
    这句话是什么意思?意思就是,即使主进程终止,子进程 p 也不会因主进程终止而终止;子进程是否终止只取决于子进程本身。
    代码3中,子进程 p 中装入的函数 clock 是死循环,子进程永远不会结束;
    p.join() 会导致主进程等待子进程 p 终止。
    (按照我的理解)所以主进程也永远不会结束,主进程的代码“卡在” p.join() 这里,没有继续往下执行。

参考文献:
Python 参考手册 - P337;
Python 核心编程 第 2 版 - P522

猜你喜欢

转载自blog.csdn.net/qq_33528613/article/details/84592608