python 多线程中的守护线程与join的用法

来源:互联网 发布:澳洲好还是加拿大 知乎 编辑:程序博客网 时间:2024/05/16 18:19

多线程:在同一个时间做多件事

守护线程:如果在程序中将子线程设置为守护线程,则该子线程会在主线程结束时自动退出,设置方式为thread.setDaemon(True),要在thread.start()之前设置,默认是false的,也就是主线程结束时,子线程依然在执行。

thread.join():在子线程完成运行之前,该子线程的父线程(一般就是主线程)将一直存在,也就是被阻塞

实例:

[python] view plain copy
  1. #!/usr/bin/python  
  2. # encoding: utf-8  
  3.   
  4.   
  5. import threading  
  6. from time import ctime,sleep  
  7.   
  8. def func1():  
  9.     count=0  
  10.     while(True):  
  11.         sleep(1)  
  12.         print 'fun1 ',count  
  13.         count = count+1  
  14.   
  15. def func2():  
  16.     count=0  
  17.     while(True):  
  18.         sleep(2)  
  19.         print 'fun2 ',count  
  20.         count = count+1  
  21.   
  22. threads = []  
  23. t1 = threading.Thread(target=func1)  
  24. threads.append(t1)  
  25. t2 = threading.Thread(target=func2)  
  26. threads.append(t2)  
  27.   
  28. if __name__ == '__main__':  
  29.     for t in threads:  
  30.         t.setDaemon(True)  
  31.         t.start()  

上面这段程序执行后,将不会有任何输出,因为子线程还没来得及执行,主线程就退出了,子线程为守护线程,所以也就退出了。

修改后的程序:

[python] view plain copy
  1. #!/usr/bin/python  
  2. # encoding: utf-8  
  3.   
  4.   
  5. import threading  
  6. from time import ctime,sleep  
  7.   
  8. def func1():  
  9.     count=0  
  10.     while(True):  
  11.         sleep(1)  
  12.         print 'fun1 '+str(count)  
  13.         count = count+1  
  14.   
  15. def func2():  
  16.     count=0  
  17.     while(True):  
  18.         sleep(2)  
  19.         print 'fun2 '+str(count)  
  20.         count = count+1  
  21.   
  22. threads = []  
  23. t1 = threading.Thread(target=func1)  
  24. threads.append(t1)  
  25. t2 = threading.Thread(target=func2)  
  26. threads.append(t2)  
  27.   
  28. if __name__ == '__main__':  
  29.     for t in threads:  
  30.         t.setDaemon(True)  
  31.         t.start()  
  32.     t.join()  

可以按照预期执行了,主要join的调用要加在循环外,不然程序只会执行第一个线程。

print 的部分改成+,是为了避免输出结果中出现类似fun1 fun2 49 这种情况,这是由于程序执行太快,用‘,’间隔相当于执行了两次print ,在这期间另一个线程也执行了print,所以导致了重叠。

0 0
原创粉丝点击