一、python多線程
因?yàn)镃Python的實(shí)現(xiàn)使用了Global Interpereter Lock(GIL),使得python中同一時(shí)刻只有一個(gè)線程在執(zhí)行,從而簡(jiǎn)化了python解釋器的實(shí)現(xiàn),且python對(duì)象模型天然地線程安全。如果你想你的應(yīng)用程序在多核的機(jī)器上使用更好的資源,建議使用multiprocessing或concurrent.futures.processpoolexecutor。但是如果你的程序是IO密集型,則使用線程仍然是很好的選擇。
二、python多線程使用的兩種方法
實(shí)例:
import threading
import time
def worker(num):
? print (threading.currentThread().getName() + ' start')
? time.sleep(10)
? print (threading.currentThread().getName() + ' running')
? print (threading.currentThread().getName() + " " + str(num))
? print (threading.currentThread().getName() + ' exit')
?
def deamon():
? print (threading.currentThread().getName() + ' start')
? time.sleep(20)
? print (threading.currentThread().getName() + ' running')
? print (threading.currentThread().getName() + ' exit')
?
print(threading.currentThread().getName())
d = threading.Thread(name='deamon', target=deamon)
d.setDaemon(True)
d.start()
w = threading.Thread(name='worker', target=worker, args=(10,))
w.start()
class myWorker(threading.Thread):
??? def __init__(self, num):?
??????? threading.Thread.__init__(self)?
??????? self.num = num?
??????? self.thread_stop = False?
??
??? def run(self):
??????? print (self.getName()+' start')
??????? time.sleep(30)
??????? print (self.getName()+' running')
??????? print (self.getName()+" " + str(self.num))
??????? print (self.getName()+' exit')
?
mw = myWorker(30)
mw.setName("MyWorker")
mw.start()
print(threading.currentThread().getName())
print("All threads:")
print("------------")
for th in threading.enumerate():
? print(th.getName())
print("------------")
d.join()
w.join()
mw.join()
print(threading.currentThread().getName())
運(yùn)行結(jié)果如下:
1)python線程使用的兩種方法:
**直接調(diào)用threading.Thread來(lái)構(gòu)造thread對(duì)象,Thread的參數(shù)如下:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})?
group為None;
target為線程將要執(zhí)行的功能函數(shù);
name為線程的名字,也可以在對(duì)象構(gòu)造后調(diào)用setName()來(lái)設(shè)定;
args為tuple類型的參數(shù),可以為多個(gè),如果只有一個(gè)也的使用tuple的形式傳入,例如(1,);
kwargs為dict類型的參數(shù),也即位命名參數(shù);
**實(shí)現(xiàn)自己的threading.Thread的子類,需要重載__init__()和run()。
2)threading.Thread對(duì)象的其他方法:
start(),用來(lái)啟動(dòng)線程;
join(), 等待直到線程結(jié)束;
setDeamon(), 設(shè)置線程為deamon線程,必須在start()調(diào)用前調(diào)用,默認(rèn)為非demon。
注意: python的主線程在沒(méi)有非deamon線程存在時(shí)就會(huì)退出。
3)threading的靜態(tài)方法:
threading.current_thread() , 用來(lái)獲得當(dāng)前的線程;
threading.enumerate() , 用來(lái)多的當(dāng)前存活的所有線程;
threading.Timer 定時(shí)器,其實(shí)是thread的一個(gè)字類型,使用如下:
def hello(): print("hello, world")??
t = Timer(30.0, hello)
t.start()
4)logging是線程安全的
logging 模塊是線程安全的,所以可以使用logging來(lái)幫助調(diào)試多線程程序。
import logging
logging.basicConfig(level=logging.DEBUG,
format="(%(threadName)-10s : %(message)s",
)
logging.debug("wait_for_event_timeout starting")
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元

