欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

對python 多線程中的守護(hù)線程與join的用法詳解

 更新時(shí)間:2019年02月18日 10:38:06   作者:thn_sweety  
今天小編就為大家分享一篇對python 多線程中的守護(hù)線程與join的用法詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

多線程:在同一個(gè)時(shí)間做多件事

守護(hù)線程:如果在程序中將子線程設(shè)置為守護(hù)線程,則該子線程會在主線程結(jié)束時(shí)自動退出,設(shè)置方式為thread.setDaemon(True),要在thread.start()之前設(shè)置,默認(rèn)是false的,也就是主線程結(jié)束時(shí),子線程依然在執(zhí)行。

thread.join():在子線程完成運(yùn)行之前,該子線程的父線程(一般就是主線程)將一直存在,也就是被阻塞

實(shí)例:

#!/usr/bin/python
# encoding: utf-8
 
 
import threading
from time import ctime,sleep
 
def func1():
 count=0
 while(True):
  sleep(1)
  print 'fun1 ',count
  count = count+1
 
def func2():
 count=0
 while(True):
  sleep(2)
  print 'fun2 ',count
  count = count+1
 
threads = []
t1 = threading.Thread(target=func1)
threads.append(t1)
t2 = threading.Thread(target=func2)
threads.append(t2)
 
if __name__ == '__main__':
 for t in threads:
  t.setDaemon(True)
  t.start()

上面這段程序執(zhí)行后,將不會有任何輸出,因?yàn)樽泳€程還沒來得及執(zhí)行,主線程就退出了,子線程為守護(hù)線程,所以也就退出了。

修改后的程序:

#!/usr/bin/python
# encoding: utf-8
 
 
import threading
from time import ctime,sleep
 
def func1():
 count=0
 while(True):
  sleep(1)
  print 'fun1 '+str(count)
  count = count+1
 
def func2():
 count=0
 while(True):
  sleep(2)
  print 'fun2 '+str(count)
  count = count+1
 
threads = []
t1 = threading.Thread(target=func1)
threads.append(t1)
t2 = threading.Thread(target=func2)
threads.append(t2)
 
if __name__ == '__main__':
 for t in threads:
  t.setDaemon(True)
  t.start()
 t.join()

可以按照預(yù)期執(zhí)行了,主要join的調(diào)用要加在循環(huán)外,不然程序只會執(zhí)行第一個(gè)線程。

print 的部分改成+,是為了避免輸出結(jié)果中出現(xiàn)類似fun1 fun2 49 這種情況,這是由于程序執(zhí)行太快,用‘,'間隔相當(dāng)于執(zhí)行了兩次print ,在這期間另一個(gè)線程也執(zhí)行了print,所以導(dǎo)致了重疊。

以上這篇對python 多線程中的守護(hù)線程與join的用法詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論