zoukankan      html  css  js  c++  java
  • python 守护进程

    主程序也是一个进程,只是我们看不到,需要借助函数打印。包括子进程也可以打印。

    threading.current_thread() 查看当前线程

    import threading
    import time
    def run(n):
        print("task ",n)
        time.sleep(2)
        print('task done',n,threading.current_thread())
    
    start_time = time.time()
    t_objs = []
    for i in range(5):
        t = threading.Thread(target=run,args=("t-%s" %i,))
        t.start()
        t_objs.append(t)
    
    
    for t in t_objs:
        t.join()
    print('--------------all threads has finished------------',threading.current_thread())
    print('cost:',time.time() - start_time )
    

     运行结果:

    task  t-0
    task  t-1
    task  t-2
    task  t-3
    task  t-4
    task done t-4 <Thread(Thread-5, started 3992)>
    task done t-3 <Thread(Thread-4, started 10176)>
    task done t-0 <Thread(Thread-1, started 6356)>
    task done t-2 <Thread(Thread-3, started 5328)>
    task done t-1 <Thread(Thread-2, started 9960)>
    --------------all threads has finished------------ <_MainThread(MainThread, started 5628)>
    cost: 2.010205030441284
    

     threading.active_count() 活跃的线程个数

    守护线程

    守护线程也是子线程,主要是服务于主线程,当主线程退出以后,守护线程也会随之结束。程序会等待非守护线程执行结束以后在退出。

    import threading
    import time
    def run(n):
        print("task ",n)
        time.sleep(2)
        print('task done',n,threading.current_thread())
    
    start_time = time.time()
    t_objs = []
    for i in range(5):
        t = threading.Thread(target=run,args=("t-%s" %i,))
        t.setDaemon(True)# 把当前线程设置成守护线程
        t.start()
        t_objs.append(t)
    
    print('--------------all threads has finished------------',threading.current_thread(),threading.active_count())
    print('cost:',time.time() - start_time )
    

     执行结果

    task  t-0
    task  t-1
    task  t-2
    task  t-3
    task  t-4
    --------------all threads has finished------------ <_MainThread(MainThread, started 8256)> 6
    cost: 0.0010001659393310547
    

     显示的是有6个子线程,但是程序并没有等待就退出了,原因是没有非守护进程。

     

  • 相关阅读:
    如何使用C++构建一个极坐标系?
    归一化 [a] 到 [b] 区间
    ffmpeg 如何转换 rgb 图片到 yuv420p?如何使用 C 语言实现 rgb24 如何转换 yuv420p ?
    如何写一个通用的网络包?
    jenkins 配置参数为tag
    jmeter函数助手digest使用简介
    RD-T: 3540 Front Impact Bumper Model
    Listary软件的使用
    Adams各种材料的接触力参数
    Spring 使用构造方法注入方式
  • 原文地址:https://www.cnblogs.com/qing-chen/p/7675975.html
Copyright © 2011-2022 走看看