Python 多線程Threading初學(xué)教程
1.1 什么是多線程 Threading
多線程可簡單理解為同時(shí)執(zhí)行多個(gè)任務(wù)。
多進(jìn)程和多線程都可以執(zhí)行多個(gè)任務(wù),線程是進(jìn)程的一部分。線程的特點(diǎn)是線程之間可以共享內(nèi)存和變量,資源消耗少(不過在Unix環(huán)境中,多進(jìn)程和多線程資源調(diào)度消耗差距不明顯,Unix調(diào)度較快),缺點(diǎn)是線程之間的同步和加鎖比較麻煩。
1.2 添加線程 Thread
導(dǎo)入模塊
import threading
獲取已激活的線程數(shù)
threading.active_count()
查看所有線程信息
threading.enumerate()
查看現(xiàn)在正在運(yùn)行的線程
threading.current_thread()
添加線程,threading.Thread()接收參數(shù)target代表這個(gè)線程要完成的任務(wù),需自行定義
def thread_job():
print('This is a thread of %s' % threading.current_thread())
def main():
thread = threading.Thread(target=thread_job,) # 定義線程
thread.start() # 讓線程開始工作
if __name__ == '__main__':
main()
1.3 join 功能
因?yàn)榫€程是同時(shí)進(jìn)行的,使用join功能可讓線程完成后再進(jìn)行下一步操作,即阻塞調(diào)用線程,直到隊(duì)列中的所有任務(wù)被處理掉。
import threading
import time
def thread_job():
print('T1 start\n')
for i in range(10):
time.sleep(0.1)
print('T1 finish\n')
def T2_job():
print('T2 start\n')
print('T2 finish\n')
def main():
added_thread=threading.Thread(target=thread_job,name='T1')
thread2=threading.Thread(target=T2_job,name='T2')
added_thread.start()
#added_thread.join()
thread2.start()
#thread2.join()
print('all done\n')
if __name__=='__main__':
main()
例子如上所示,當(dāng)不使用join功能的時(shí)候,結(jié)果如下圖所示:

當(dāng)執(zhí)行了join功能之后,T1運(yùn)行完之后才運(yùn)行T2,之后再運(yùn)行print(‘a(chǎn)ll done')

1.4 儲存進(jìn)程結(jié)果 queue
queue是python標(biāo)準(zhǔn)庫中的線程安全的隊(duì)列(FIFO)實(shí)現(xiàn),提供了一個(gè)適用于多線程編程的先進(jìn)先出的數(shù)據(jù)結(jié)構(gòu),即隊(duì)列,用來在生產(chǎn)者和消費(fèi)者線程之間的信息傳遞
(1)基本FIFO隊(duì)列
class queue.Queue(maxsize=0)
maxsize是整數(shù),表明隊(duì)列中能存放的數(shù)據(jù)個(gè)數(shù)的上限,達(dá)到上限時(shí),插入會(huì)導(dǎo)致阻塞,直至隊(duì)列中的數(shù)據(jù)被消費(fèi)掉,如果maxsize小于或者等于0,隊(duì)列大小沒有限制
(2)LIFO隊(duì)列 last in first out后進(jìn)先出
class queue.LifoQueue(maxsize=0)
(3)優(yōu)先級隊(duì)列
class queue.PriorityQueue(maxsize=0)
視頻中的代碼,看的還不是特別明白
import threading
import time
from queue import Queue
def job(l,q):
for i in range(len(l)):
l[i]=l[i]**2
q.put(l)
def multithreading():
q=Queue()
threads=[]
data=[[1,2,3],[3,4,5],[4,5,6],[5,6,7]]
for i in range(4):
t=threading.Thread(target=job,args=(data[i],q))
t.start()
threads.append(t)
for thread in threads:
thread.join()
results=[]
for _ in range(4):
results.append(q.get())
print(results)
if __name__=='__main__':
multithreading()
運(yùn)行結(jié)果如下所示


圖片截取來源:http://www.cnblogs.com/itogo/p/5635629.html
1.5 GIL 不一定有效率
Global Interpreter Lock全局解釋器鎖,python的執(zhí)行由python虛擬機(jī)(也成解釋器主循環(huán))控制,GIL的控制對python虛擬機(jī)的訪問,保證在任意時(shí)刻,只有一個(gè)線程在解釋器中運(yùn)行。在多線程環(huán)境中能,python虛擬機(jī)按照以下方式執(zhí)行:
1.設(shè)置 GIL
2.切換到一個(gè)線程去運(yùn)行
3.運(yùn)行:
a.指定數(shù)量的字節(jié)碼指令,或
b.線程主動(dòng)讓出控制(可以調(diào)用time.sleep(0))
4.把線程設(shè)置為睡眠狀態(tài)
5.解鎖GIL
6.重復(fù)1-5
在調(diào)用外部代碼(如C/C++擴(kuò)展函數(shù))的時(shí)候,GIL將會(huì)被鎖定,直到這個(gè)函數(shù)結(jié)束為止(由于在這期間沒有python的字節(jié)碼被運(yùn)行,所以不會(huì)做線程切換)。
下面為視頻中所舉例的代碼,將一個(gè)數(shù)擴(kuò)大4倍,分為正常方式、以及分配給4個(gè)線程去做,發(fā)現(xiàn)耗時(shí)其實(shí)并沒有相差太多量級。
import threading
from queue import Queue
import copy
import time
def job(l, q):
res = sum(l)
q.put(res)
def multithreading(l):
q = Queue()
threads = []
for i in range(4):
t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i)
t.start()
threads.append(t)
[t.join() for t in threads]
total = 0
for _ in range(4):
total += q.get()
print(total)
def normal(l):
total = sum(l)
print(total)
if __name__ == '__main__':
l = list(range(1000000))
s_t = time.time()
normal(l*4)
print('normal: ',time.time()-s_t)
s_t = time.time()
multithreading(l)
print('multithreading: ', time.time()-s_t)
運(yùn)行結(jié)果為:


1.6 線程鎖 Lock
如果線程1得到了結(jié)果,想要讓線程2繼續(xù)使用1的結(jié)果進(jìn)行處理,則需要對1lock,等到1執(zhí)行完,再開始執(zhí)行線程2。一般來說對share memory即對共享內(nèi)存進(jìn)行加工處理時(shí)會(huì)用到lock。
import threading
def job1():
global A, lock #全局變量
lock.acquire() #開始lock
for i in range(10):
A += 1
print('job1', A)
lock.release() #釋放
def job2():
global A, lock
lock.acquire()
for i in range(10):
A += 10
print('job2', A)
lock.release()
if __name__ == '__main__':
lock = threading.Lock()
A = 0
t1 = threading.Thread(target=job1)
t2 = threading.Thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()
運(yùn)行結(jié)果如下所示:

總結(jié)
以上所述是小編給大家介紹的Python 多線程Threading初學(xué)教程,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- python多線程threading.Lock鎖用法實(shí)例
- Python多線程threading和multiprocessing模塊實(shí)例解析
- Python多線程threading模塊用法實(shí)例分析
- Python多線程threading join和守護(hù)線程setDeamon原理詳解
- python 多線程中子線程和主線程相互通信方法
- python子線程退出及線程退出控制的代碼
- python主線程捕獲子線程的方法
- python從子線程中獲得返回值的方法
- python主線程與子線程的結(jié)束順序?qū)嵗馕?/a>
- Python 多線程,threading模塊,創(chuàng)建子線程的兩種方式示例
- python實(shí)現(xiàn)守護(hù)進(jìn)程、守護(hù)線程、守護(hù)非守護(hù)并行
- Python多線程Threading、子線程與守護(hù)線程實(shí)例詳解
相關(guān)文章
深入探討Python復(fù)合型數(shù)據(jù)的常見陷阱與避免方法
在Python中,復(fù)合型數(shù)據(jù)(例如列表、元組、集合和字典)是非常常用的數(shù)據(jù)類型,本文將深入探討Python復(fù)合型數(shù)據(jù)的常見陷阱,并提供一些避免這些問題的實(shí)用建議和技巧,希望對大家有所幫助2024-03-03
Python3.5裝飾器原理及應(yīng)用實(shí)例詳解
這篇文章主要介紹了Python3.5裝飾器原理及應(yīng)用,結(jié)合具體實(shí)例形式詳細(xì)分析了Python3.5裝飾器的概念、原理、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-04-04
django實(shí)現(xiàn)登錄時(shí)候輸入密碼錯(cuò)誤5次鎖定用戶十分鐘
這篇文章主要介紹了django實(shí)現(xiàn)登錄時(shí)候輸入密碼錯(cuò)誤5次鎖定用戶十分鐘,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
Python實(shí)用庫 PrettyTable 學(xué)習(xí)筆記
這篇文章主要介紹了Python實(shí)用庫 PrettyTable 學(xué)習(xí)筆記,結(jié)合實(shí)例形式分析了Python表格操作庫PrettyTable的安裝、使用技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-08-08
python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明
這篇文章主要介紹了python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
對Python3中的print函數(shù)以及與python2的對比分析
下面小編就為大家分享一篇對Python3中的print函數(shù)以及與python2的對比分析,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
Python深度學(xué)習(xí)之Unet?語義分割模型(Keras)
這篇文章主要介紹了語義分割任務(wù)中Unet一個(gè)有意思的模型-Keras。Keras是一個(gè)由Python編寫的開源人工神經(jīng)網(wǎng)絡(luò)庫,可進(jìn)行深度學(xué)習(xí)模型的設(shè)計(jì)、調(diào)試、評估、應(yīng)用和可視化。感興趣的小伙伴快來跟隨小編一起學(xué)習(xí)一下吧2021-12-12

