Python多線程同步Lock、RLock、Semaphore、Event實(shí)例
一、多線程同步
由于CPython的python解釋器在單線程模式下執(zhí)行,所以導(dǎo)致python的多線程在很多的時(shí)候并不能很好地發(fā)揮多核cpu的資源。大部分情況都推薦使用多進(jìn)程。
python的多線程的同步與其他語(yǔ)言基本相同,主要包含:
Lock & RLock :用來(lái)確保多線程多共享資源的訪問(wèn)。
Semaphore : 用來(lái)確保一定資源多線程訪問(wèn)時(shí)的上限,例如資源池。
Event : 是最簡(jiǎn)單的線程間通信的方式,一個(gè)線程可以發(fā)送信號(hào),其他的線程接收到信號(hào)后執(zhí)行操作。
二、實(shí)例
1)Lock & RLock
Lock對(duì)象的狀態(tài)可以為locked和unlocked
使用acquire()設(shè)置為locked狀態(tài);
使用release()設(shè)置為unlocked狀態(tài)。
如果當(dāng)前的狀態(tài)為unlocked,則acquire()會(huì)將狀態(tài)改為locked然后立即返回。當(dāng)狀態(tài)為locked的時(shí)候,acquire()將被阻塞直到另一個(gè)線程中調(diào)用release()來(lái)將狀態(tài)改為unlocked,然后acquire()才可以再次將狀態(tài)置為locked。
Lock.acquire(blocking=True, timeout=-1),blocking參數(shù)表示是否阻塞當(dāng)前線程等待,timeout表示阻塞時(shí)的等待時(shí)間 。如果成功地獲得lock,則acquire()函數(shù)返回True,否則返回False,timeout超時(shí)時(shí)如果還沒(méi)有獲得lock仍然返回False。
實(shí)例:(確保只有一個(gè)線程可以訪問(wèn)共享資源)
import threading
import time
num = 0
lock = threading.Lock()
def func(st):
global num
print (threading.currentThread().getName() + ' try to acquire the lock')
if lock.acquire():
print (threading.currentThread().getName() + ' acquire the lock.' )
print (threading.currentThread().getName() +" :%s" % str(num) )
num += 1
time.sleep(st)
print (threading.currentThread().getName() + ' release the lock.' )
lock.release()
t1 = threading.Thread(target=func, args=(8,))
t2 = threading.Thread(target=func, args=(4,))
t3 = threading.Thread(target=func, args=(2,))
t1.start()
t2.start()
t3.start()
結(jié)果:
RLock與Lock的區(qū)別是:RLock中除了狀態(tài)locked和unlocked外還記錄了當(dāng)前l(fā)ock的owner和遞歸層數(shù),使得RLock可以被同一個(gè)線程多次acquire()。
2)Semaphore
Semaphore管理一個(gè)內(nèi)置的計(jì)數(shù)器,
每當(dāng)調(diào)用acquire()時(shí)內(nèi)置計(jì)數(shù)器-1;
調(diào)用release() 時(shí)內(nèi)置計(jì)數(shù)器+1;
計(jì)數(shù)器不能小于0;當(dāng)計(jì)數(shù)器為0時(shí),acquire()將阻塞線程直到其他線程調(diào)用release()。
實(shí)例:(同時(shí)只有2個(gè)線程可以獲得semaphore,即可以限制最大連接數(shù)為2):
import threading
import time
semaphore = threading.Semaphore(2)
def func():
if semaphore.acquire():
for i in range(5):
print (threading.currentThread().getName() + ' get semaphore')
semaphore.release()
print (threading.currentThread().getName() + ' release semaphore')
for i in range(4):
t1 = threading.Thread(target=func)
t1.start()
結(jié)果:
3) Event
Event內(nèi)部包含了一個(gè)標(biāo)志位,初始的時(shí)候?yàn)閒alse。
可以使用使用set()來(lái)將其設(shè)置為true;
或者使用clear()將其從新設(shè)置為false;
可以使用is_set()來(lái)檢查標(biāo)志位的狀態(tài);
另一個(gè)最重要的函數(shù)就是wait(timeout=None),用來(lái)阻塞當(dāng)前線程,直到event的內(nèi)部標(biāo)志位被設(shè)置為true或者timeout超時(shí)。如果內(nèi)部標(biāo)志位為true則wait()函數(shù)理解返回。
實(shí)例: (線程間相互通信)
import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format="(%(threadName)-10s : %(message)s",
)
def wait_for_event_timeout(e, t):
"""Wait t seconds and then timeout"""
while not e.isSet():
logging.debug("wait_for_event_timeout starting")
event_is_set = e.wait(t)
logging.debug("event set: %s" % event_is_set)
if event_is_set:
logging.debug("processing event")
else:
logging.debug("doing other work")
e = threading.Event()
t2 = threading.Thread(name="nonblock",
target=wait_for_event_timeout,args=(e, 2))
t2.start()
logging.debug("Waiting before calling Event.set()")
time.sleep(7)
e.set()
logging.debug("Event is set")
運(yùn)行結(jié)果:
三、其他
1) 線程局部變量
線程局部變量的值是跟線程相關(guān)的,區(qū)別與全局的變量。使用非常簡(jiǎn)單如下:
mydata = threading.local()
mydata.x = 1
2)對(duì)Lock,semaphore,condition等使用with關(guān)鍵字代替手動(dòng)調(diào)用acquire()和release()。
相關(guān)文章
python中的import絕對(duì)導(dǎo)入與相對(duì)導(dǎo)入詳解
這篇文章主要介紹了python中的import絕對(duì)導(dǎo)入與相對(duì)導(dǎo)入詳解,在使用python做一些簡(jiǎn)單項(xiàng)目時(shí),import一般不會(huì)出現(xiàn)問(wèn)題,但項(xiàng)目結(jié)構(gòu)復(fù)雜時(shí),import可能發(fā)生報(bào)錯(cuò),需要的朋友可以參考下2023-11-11Django?ORM?F對(duì)象和Q對(duì)象查詢(xún)
Django提供了兩個(gè)非常有用的工具:F對(duì)象和Q對(duì)象,方便了在一些特殊場(chǎng)景下的查詢(xún)過(guò)程,這篇文章主要介紹了Django?ORM?F對(duì)象和Q對(duì)象查詢(xún),需要的朋友可以參考下2022-10-10Django Python 獲取請(qǐng)求頭信息Content-Range的方法
今天小編就為大家分享一篇Django Python 獲取請(qǐng)求頭信息Content-Range的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08淺談Python生成器generator之next和send的運(yùn)行流程(詳解)
下面小編就為大家?guī)?lái)一篇淺談Python生成器generator之next和send的運(yùn)行流程(詳解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05Appium+python自動(dòng)化之連接模擬器并啟動(dòng)淘寶APP(超詳解)
這篇文章主要介紹了Appium+python自動(dòng)化之 連接模擬器并啟動(dòng)淘寶APP(超詳解)本文以淘寶app為例,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2019-06-06