Python中線程鎖的使用介紹
前言
當有多個線程,且它們同時訪問同一資源時,需要考慮如何避免線程沖突。解決辦法是使用線程鎖。鎖由Python的threading模塊提供,并且它最多被一個線程所持有。當一個線程試圖獲取一個已經鎖在資源上的鎖時,該線程通常會暫停運行,直到這個鎖被釋放。看看下面的不具備鎖功能的例子:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: LiveEveryDay
import threading
total = 0
def update_total(amount):
global total
total += amount
print(total)
if __name__ == '__main__':
for i in range(10):
my_thread = threading.Thread(target=update_total, args=(5,))
my_thread.start()
''' ------ Running Results ------
510
15
20
25
30
3540
45
50
'''如果往以上代碼添加 time.sleep 函數并給出不同長度的時間,可能會讓這個例子更有意思。無論如何,這里的問題是,一個線程可能已經調用 update_total 函數并且還沒有更新完成,此時另一個線程也有可能調用它并且嘗試更新內容。根據操作執(zhí)行順序的不同,該值可能只被增加一次。
給它添加鎖后:
方式一:使用try/finally,確保鎖肯定會被釋放。
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: LiveEveryDay
import threading
total = 0
lock = threading.Lock()
def update_total(amount):
global total
lock.acquire()
try:
total += amount
finally:
print(total)
lock.release()
if __name__ == '__main__':
for i in range(10):
my_thread = threading.Thread(target=update_total, args=(5,))
my_thread.start()
''' ------ Running Results ------
5
10
15
20
25
30
35
40
45
50
'''如上,在我們做任何處理之前就獲取鎖。然后嘗試更新 total 的值,最后打印出 total 的當前值并釋放鎖。
方式二:with語句避免使用try/finally。
事實上,我們可以使用 Python 的 with 語句避免使用 try/finally 這種較為繁瑣的語句:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Author: LiveEveryDay
import threading
total = 0
lock = threading.Lock()
def update_total(amount):
global total
with lock:
total += amount
print(total)
if __name__ == '__main__':
for i in range(10):
my_thread = threading.Thread(target=update_total, args=(5,))
my_thread.start()
''' ------ Running Results ------
5
10
15
20
25
30
35
40
45
50
'''總結
到此這篇關于Python中線程鎖的使用介紹的文章就介紹到這了,更多相關Python線程鎖內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pytorch中的torch.nn.Conv2d()函數圖文詳解
這篇文章主要給大家介紹了關于pytorch中torch.nn.Conv2d()函數的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2022-02-02
解決Scrapy安裝錯誤:Microsoft Visual C++ 14.0 is required...
下面小編就為大家?guī)硪黄鉀QScrapy安裝錯誤:Microsoft Visual C++ 14.0 is required...的問題。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
解決windows上安裝tensorflow時報錯,“DLL load failed: 找不到指定的模塊”的問題
這篇文章主要介紹了解決windows上安裝tensorflow時報錯,“DLL load failed: 找不到指定的模塊”的問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
python?裝飾器(Decorators)原理說明及操作代碼
裝飾器(Decorators)是 Python 的一個重要部分,本文由淺入深給大家介紹了python?裝飾器Decorators原理,感興趣的朋友跟隨小編一起看看吧2021-12-12

