Python多執行緒之執行緒建立和終止

2021-06-26 11:25:41 字數 4891 閱讀 5347

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」

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()

執行結果是:

-------stop subthread example with event:----------   

<_mainthread(mainthread, started 2436)>alive

testa.txt closed? false

testb.txt closed? false

subthreada alive

subthreadb alive

<_mainthread(mainthread, started 2436)>send stop signal

close opened file in subthreada

close opened file in subthreadb

subthreada stoped

subthreadb stoped

<_mainthread(mainthread, started 2436)>stoped

after a stoped, testa.txt closed? true

after a stoped, testb.txt closed? true

-------daemon stop subthread example :----------

<_mainthread(mainthread, started 2436)>alive

testa.txt closed? false

subthreada alive

subthreada stoped

<_mainthread(mainthread, started 2436)>stoped

after a stoped, testa.txt closed? false

you see the differents, the resource in subthread may not released with setdaemon()

Linux 多執行緒之執行緒的建立和退出

include apue.h 1.main函式的執行緒稱為初始執行緒或主線程,主線程在main函式返回的時候,會導致 整個程序結束。可以在主線程中使用pthread exit函式 退出主線程 如此,程序會等待所有的執行緒結束時候才終止 struct person void thread fun vo...

多執行緒之建立

建立執行緒的構造方法 1.thread 分配新的 thread 物件。2.thread runnable target 分配新的 thread 物件。3.thread string name 建立乙個執行緒,並給該執行緒物件分配乙個名字。4.thread runnable target,string...

Linux多執行緒之執行緒建立

1.函式 include intpthread create pthread t restrict thread,const pthread attr t restrict attr,void start routine void void restrict arg 引數 thread 為執行緒id...