python多線程操作實(shí)例
一、python多線程
因?yàn)镃Python的實(shí)現(xiàn)使用了Global Interpereter Lock(GIL),使得python中同一時刻只有一個線程在執(zhí)行,從而簡化了python解釋器的實(shí)現(xiàn),且python對象模型天然地線程安全。如果你想你的應(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來構(gòu)造thread對象,Thread的參數(shù)如下:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
group為None;
target為線程將要執(zhí)行的功能函數(shù);
name為線程的名字,也可以在對象構(gòu)造后調(diào)用setName()來設(shè)定;
args為tuple類型的參數(shù),可以為多個,如果只有一個也的使用tuple的形式傳入,例如(1,);
kwargs為dict類型的參數(shù),也即位命名參數(shù);
**實(shí)現(xiàn)自己的threading.Thread的子類,需要重載__init__()和run()。
2)threading.Thread對象的其他方法:
start(),用來啟動線程;
join(), 等待直到線程結(jié)束;
setDeamon(), 設(shè)置線程為deamon線程,必須在start()調(diào)用前調(diào)用,默認(rèn)為非demon。
注意: python的主線程在沒有非deamon線程存在時就會退出。
3)threading的靜態(tài)方法:
threading.current_thread() , 用來獲得當(dāng)前的線程;
threading.enumerate() , 用來多的當(dāng)前存活的所有線程;
threading.Timer 定時器,其實(shí)是thread的一個字類型,使用如下:
def hello(): print("hello, world")
t = Timer(30.0, hello)
t.start()
4)logging是線程安全的
logging 模塊是線程安全的,所以可以使用logging來幫助調(diào)試多線程程序。
import logging
logging.basicConfig(level=logging.DEBUG,
format="(%(threadName)-10s : %(message)s",
)
logging.debug("wait_for_event_timeout starting")
相關(guān)文章
Python 判斷是否為質(zhì)數(shù)或素數(shù)的實(shí)例
下面小編就為大家?guī)硪黄狿ython 判斷是否為質(zhì)數(shù)或素數(shù)的實(shí)例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10Python Socket編程實(shí)現(xiàn)猜數(shù)字游戲交互體驗(yàn)
當(dāng)利用Python的Socket編程創(chuàng)建一個猜數(shù)字游戲時,需要分別實(shí)現(xiàn)服務(wù)器端和客戶端的邏輯,本文將詳細(xì)描述這兩個部分的功能和代碼片段2024-01-01Python threading模塊中l(wèi)ock與Rlock的使用詳細(xì)講解
python的thread模塊是比較底層的模塊,python的threading模塊是對thread做了一些包裝的,可以更加方便的被使用。這篇文章主要介紹了Python threading模塊中l(wèi)ock與Rlock的使用2022-10-10Python實(shí)現(xiàn)構(gòu)建一個儀表板的示例代碼
這篇文章主要為大家詳細(xì)介紹了Python如何實(shí)現(xiàn)構(gòu)建一個儀表板,文中的示例代碼講解詳細(xì),具有一定的參考價值,感興趣的小伙伴可以了解一下2023-03-03Python區(qū)塊鏈創(chuàng)建Genesis Block教程
這篇文章主要為大家介紹了Python區(qū)塊鏈創(chuàng)建Genesis Block教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05Pycharm github配置實(shí)現(xiàn)過程圖解
這篇文章主要介紹了Pycharm github配置實(shí)現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10python中List添加與刪除元素的幾種方法實(shí)例
列表基本上是?Python?中最常用的數(shù)據(jù)結(jié)構(gòu)之一了,并且刪除操作也是經(jīng)常使用的,下面這篇文章主要給大家介紹了關(guān)于python中List添加與刪除元素的相關(guān)資料,需要的朋友可以參考下2022-09-09