亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

對python 多線程中的守護線程與join的用法詳解

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

多線程:在同一個時間做多件事

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

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

實例:

#!/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í)行后,將不會有任何輸出,因為子線程還沒來得及執(zhí)行,主線程就退出了,子線程為守護線程,所以也就退出了。

修改后的程序:

#!/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í)行第一個線程。

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

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

相關(guān)文章

最新評論