Python使用functools實現(xiàn)注解同步方法
在 Python 中沒有類似 Java 中使用的 synchronized 關鍵字來同步方法,因此在 Python 中要實現(xiàn)同步方法,通常我們是使用 threading.Lock() 來實現(xiàn)。在進入函數(shù)的地方獲取鎖,出函數(shù)的時候釋放鎖,這樣實現(xiàn)代碼看起好非常不好看。另外網(wǎng)上也有人給出了其它幾種實現(xiàn)方式,但看起來都不美氣。
今天我在做項目的時候突然想到是不是可以通過 functools 來實現(xiàn)通過注解來標注方法為同步方法。
首先要求自己的類中有一個鎖對象并且在類初始化的時候初始化這個鎖對象,比如:
class MyWorker(object): def __init__(self): self.lock = threading.Lock() ... ...
然后創(chuàng)建一個 synchronized 函數(shù),這個函數(shù)裝飾具體對象的具體方法,將方法放到獲取/釋放鎖之間來運行,如下
def synchronized(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): with self.lock: return func(self, *args, **kwargs) return wrapper
最后在需要使用同步的方法上使用 @synchronized 來標準方法是同步方法,比如:
@synchronized def test(self): ...
下面是一個完整例子,僅供參考:
import threading import functools import time def synchronized(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): with self.lock: return func(self, *args, **kwargs) return wrapper class MyWorker(object): def __init__(self): self.lock = threading.Lock() self.idx = 0 @synchronized def test1(self): for i in range(1, 11): self.idx = self.idx + 1 print "Test1: " + str(self.idx) time.sleep(1) @synchronized def test2(self): for i in range(1, 11): self.idx = self.idx + 1 print "Test2: " + str(self.idx) time.sleep(1) @synchronized def test3(self): for i in range(1, 11): self.idx = self.idx + 1 print "Test3: " + str(self.idx) time.sleep(1) worker = MyWorker() threading.Thread(target=worker.test1).start() threading.Thread(target=worker.test2).start() threading.Thread(target=worker.test3).start()
總結
以上所述是小編給大家介紹的Python使用functools實現(xiàn)注解同步方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Python functools模塊學習總結
- Python中functools模塊的常用函數(shù)解析
- Python中functools模塊函數(shù)解析
- Python3標準庫之functools管理函數(shù)的工具詳解
- Python編程functools模塊創(chuàng)建修改的高階函數(shù)解析
- Python的functools模塊使用及說明
- Python庫functools示例詳解
- Python中的functools partial詳解
- python高階函數(shù)functools模塊的具體使用
- Python中Functools模塊的高級操作詳解
- Python函數(shù)式編程模塊functools的使用與實踐
相關文章
Python實現(xiàn)多組數(shù)據(jù)三維繪圖系統(tǒng)
這篇文章主要為大家詳細介紹了如何利用Python實現(xiàn)多組數(shù)據(jù)三維繪圖系統(tǒng),文中的示例代碼講解詳細,具有一定的學習價值,感興趣的小伙伴可以了解下2023-08-08Python中的map()函數(shù)和reduce()函數(shù)的用法
這篇文章主要介紹了Python中的map()函數(shù)和reduce()函數(shù)的用法,代碼基于Python2.x版本,需要的朋友可以參考下2015-04-04Python Pickle 實現(xiàn)在同一個文件中序列化多個對象
今天小編就為大家分享一篇Python Pickle 實現(xiàn)在同一個文件中序列化多個對象,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12python實戰(zhàn)之PyQt5實現(xiàn)漫畫臉
本文詳細講解了python實戰(zhàn)之PyQt5實現(xiàn)漫畫臉的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-12-12瀏覽器常用基本操作之python3+selenium4自動化測試(基礎篇3)
瀏覽器常用基本操作有很多種,今天給大家介紹python3+selenium4自動化測試的操作方法,是最最基礎的一篇,對python3 selenium4自動化測試相關知識感興趣的朋友一起看看吧2021-05-05基于Python 中函數(shù)的 收集參數(shù) 機制
今天小編就為大家分享一篇基于Python 中函數(shù)的 收集參數(shù) 機制,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12