原因:了解进程的运行活动,只能实例化子进程。
# coding=utf-8
import logging
import os
import time
from multiprocessing import Process
x1, x2 = 3, 7
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [*] %(processName)s %(message)s"
)
def run_add (x1, x2):
time.sleep(5)
logging.info(f"子进程ID:{os.getpid()}")
logging.info(f'x1 + x2 = {x1 + x2}')
logging.info("----------the end------[*]")
if __name__ == '__main__':
logging.info("--------starting-----[*]")
p = Process(target=run_add, args=(x1, x2))
p.daemon = True # 如果没有join()方法,当主进程退出时,它会尝试终止其所有守护进程的子进程。
logging.info(f"子进程是否存活:{p.is_alive()}")
p.start()
logging.info(f"子进程是否存活:{p.is_alive()}")
logging.info(f"子进程ID:{p.pid}")
logging.info(f"子进程的身份验证密钥:{p.authkey}")
logging.info(f"子进程系统对象的数字句柄:{p.sentinel}")
# p.terminate() # 终止子进程
p.join() # 等待子进程结束后再继续往下运行,通常用于进程间的同步。
logging.info(f"主进程ID:{os.getpid()}")
logging.info(f'x1 * x2 = {x1 * x2}', )
logging.info("--------the end------[*]")
输出:
2019-10-03 14:43:41,554 [*] MainProcess --------starting-----[*]
2019-10-03 14:43:41,554 [*] MainProcess 子进程是否存活:False
2019-10-03 14:43:41,570 [*] MainProcess 子进程是否存活:True
2019-10-03 14:43:41,570 [*] MainProcess 子进程ID:3704
2019-10-03 14:43:41,570 [*] MainProcess 子进程的身份验证密钥:b'V_\xe3\xce7\xa3\xa2r0iy-\xd6\xcf)"\x84\x0c\xbd\x13h\xe8\x90\xb8\x064\xa9\x8c\x1c0\xc7%'
2019-10-03 14:43:41,570 [*] MainProcess 子进程系统对象的数字句柄:440
2019-10-03 14:43:46,639 [*] Process-1 子进程ID:3704
2019-10-03 14:43:46,639 [*] Process-1 x1 + x2 = 10
2019-10-03 14:43:46,639 [*] Process-1 ----------the end------[*]
2019-10-03 14:43:46,660 [*] MainProcess 主进程ID:7344
2019-10-03 14:43:46,660 [*] MainProcess x1 * x2 = 21
2019-10-03 14:43:46,660 [*] MainProcess --------the end------[*]