前言:
主要分析下面的问题:
- 主线程启线程 主线程执行完毕,会关闭子线程吗?
- 子线程启线程 主线程执行完毕,会结束吗?
- 主进程启动进程,主进程执行完毕,会怎样?
- 子进程启动进程,进程执行完毕,又会如何?
1、主线程启线程
示例1.1
import time
import threading
def function():
time.sleep(2)
print('sub thread [%s] execute done' % threading.currentThread().ident)
def main():
threading.Thread(target=function).start()
print('main thread [%s] execute done'%threading.currentThread().ident)
if __name__ == '__main__':
main()
# main thread [11920] execute done
# sub thread [8876] execute done
主线程执行完毕,等待子线程执行;若想主线程执行完毕,直接退出,需设置守护线程
示例1.2
import time
import threading
def function():
time.sleep(2)
print('sub thread [%s] execute done' % threading.currentThread().ident)
def main():
t = threading.Thread(target=function)
t.setDaemon(True)
t.start()
print('main thread [%s] execute done'%threading.currentThread().ident)
if __name__ == '__main__':
main()
# main thread [3052] execute done
2、子线程启动线程
示例2.1
import time
import threading
def function():
time.sleep(2)
threading.Thread(target=subfunction).start()
print('sub thread [%s] execute done' % threading.currentThread().ident)
def subfunction():
time.sleep(2)
print('sub thread [%s] execute done' % threading.currentThread().ident)
def main():
threading.Thread(target=function).start()
print('main thread [%s] execute done'%threading.currentThread().ident)
if __name__ == '__main__':
main()
# main thread [2288] execute done
# sub thread [9556] execute done
# sub thread [12156] execute done
如示例1.1一致,主线程会等待子子线程执行完毕,然后关闭
3、主进程启动进程
示例2.1
import os
import time
import multiprocessing
def function():
time.sleep(2)
print('sub process [%s] execute done' % os.getpid())
def main():
multiprocessing.Process(target=function).start()
print('main process [%s] execute done'%os.getpid())
if __name__ == '__main__':
main()
# main process [5628] execute done
# sub process [11060] execute done
主进程会等待子进程执行完毕后关闭
4、子进程启动进程
示例4.1
import os
import time
import multiprocessing
def function():
time.sleep(2)
print('sub process [%s] execute done' % os.getpid())
def main():
pid = os.fork()
print(pid)
if pid > 0:
return
multiprocessing.Process(target=function).start()
print('main process [%s] execute done'%os.getpid())
if __name__ == '__main__':
main()
# 20533
# 0
# main process [20533] execute done
# sub process[20534] execute done
子进程会等待进程执行完毕后关闭