Python开发【笔记】:关于子线程(子进程)与主线程(主进程)的关联

前言:

主要分析下面的问题:

  • 主线程启线程  主线程执行完毕,会关闭子线程吗?
  • 子线程启线程  主线程执行完毕,会结束吗?
  • 主进程启动进程,主进程执行完毕,会怎样?
  • 子进程启动进程,进程执行完毕,又会如何?

 

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

子进程会等待进程执行完毕后关闭 

 

 

转载于:https://www.cnblogs.com/lianzhilei/p/9620246.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值