国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python線程創建和終止實例代碼

2020-02-22 22:55:17
字體:
來源:轉載
供稿:網友

python主要是通過thread和threading這兩個模塊來實現多線程支持。

python的thread模塊是比較底層的模塊,python的threading模塊是對thread做了一些封裝,能夠更加方便的被使用。可是python(cpython)因為GIL的存在無法使用threading充分利用CPU資源,假設想充分發揮多核CPU的計算能力須要使用multiprocessing模塊(Windows下使用會有諸多問題)。

假設在對線程應用有較高的要求時能夠考慮使用Stackless Python來完畢。Stackless Python是Python的一個改動版本號,對多線程編程有更好的支持,提供了對微線程的支持。微線程是輕量級的線程,在多個線程間切換所需的時間很多其它,占用資源也更少。

通過threading模塊創建新的線程有兩種方法:一種是通過threading.Thread(Target=executable Method)-即傳遞給Thread對象一個可運行方法(或對象);另外一種是繼承threading.Thread定義子類并重寫run()方法。另外一種方法中,唯一必須重寫的方法是run(),可依據需要決定是否重寫__init__()。值得注意的是,若要重寫__init__(),父類的__init__()必需要在函數第一行調用,否則會觸發錯誤“AssertionError: Thread.__init__() not called”

Python threading模塊不同于其它語言之處在于它沒有提供線程的終止方法,通過Python threading.Thread()啟動的線程彼此是獨立的。若在線程A中啟動了線程B,那么A、B是彼此獨立執行的線程。若想終止線程A的同一時候強力終止線程B。一個簡單的方法是通過在線程A中調用B.setDaemon(True)實現。

但這樣帶來的問題是:線程B中的資源(打開的文件、傳輸數據等)可能會沒有正確的釋放。所以setDaemon()并不是一個好方法,更為妥當的方式是通過Event機制。以下這段程序體現了setDaemon()和Event機制終止子線程的差別。

import threading import time class mythread(threading.Thread):  def __init__(self,stopevt = None,File=None,name = 'subthread',Type ='event'):   threading.Thread.__init__(self)   self.stopevt = stopevt   self.name = name   self.File = File   self.Type = Type          def Eventrun(self):   while not self.stopevt.isSet():    print self.name +' alive/n'    time.sleep(2)   if self.File:    print 'close opened file in '+self.name+'/n'    self.File.close()   print self.name +' stoped/n'    def Daemonrun(self):   D = mythreadDaemon(self.File)   D.setDaemon(True)   while not self.stopevt.isSet():    print self.name +' alive/n'    time.sleep(2)   print self.name +' stoped/n'  def run(self):   if self.Type == 'event': self.Eventrun()   else: self.Daemonrun() class mythreadDaemon(threading.Thread):  def __init__(self,File=None,name = 'Daemonthread'):   threading.Thread.__init__(self)   self.name = name   self.File = File  def run(self):   while True:    print self.name +' alive/n'    time.sleep(2)   if self.File:    print 'close opened file in '+self.name+'/n'    self.File.close()   print self.name +' stoped/n'    def evtstop():  stopevt = threading.Event()  FileA = open('testA.txt','w')  FileB = open('testB.txt','w')  A = mythread(stopevt,FileA,'subthreadA')  B = mythread(stopevt,FileB,'subthreadB')  print repr(threading.currentThread())+'alive/n'  print FileA.name + ' closed? '+repr(FileA.closed)+'/n'  print FileB.name + ' closed? '+repr(FileB.closed)+'/n'  A.start()  B.start()  time.sleep(1)  print repr(threading.currentThread())+'send stop signal/n'  stopevt.set()  A.join()  B.join()  print repr(threading.currentThread())+'stoped/n'  print 'after A stoped, '+FileA.name + ' closed? '+repr(FileA.closed)+'/n'  print 'after A stoped, '+FileB.name + ' closed? '+repr(FileB.closed)+'/n' def daemonstop():  stopevt = threading.Event()  FileA = open('testA.txt','r')  A = mythread(stopevt,FileA,'subthreadA',Type = 'Daemon')  print repr(threading.currentThread())+'alive/n'  print FileA.name + ' closed? '+repr(FileA.closed)+'/n'  A.start()  time.sleep(1)  stopevt.set()  A.join()  print repr(threading.currentThread())+'stoped/n'  print 'after A stoped, '+FileA.name + ' closed? '+repr(FileA.closed)+'/n'  if not FileA.closed:   print 'You see the differents, the resource in subthread may not released with setDaemon()'   FileA.close() if __name__ =='__main__':  print '-------stop subthread example with Event:----------/n'  evtstop()  print '-------Daemon stop subthread example :----------/n'  daemonstop()             
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 酉阳| 泾川县| 乐都县| 万宁市| 米林县| 濮阳市| 江源县| 郁南县| 炎陵县| 鸡东县| 广宁县| 镇坪县| 鹤岗市| 镇雄县| 梁河县| 阜新| 布拖县| 慈利县| 临朐县| 博罗县| 邮箱| 姚安县| 榆树市| 昭通市| 福贡县| 游戏| 咸宁市| 双辽市| 黄浦区| 黑龙江省| 贺州市| 宝丰县| 乐平市| 宝应县| 安达市| 航空| 平度市| 宣威市| 河北省| 宁安市| 确山县|