Python使用functools實現(xiàn)注解同步方法
在 Python 中沒有類似 Java 中使用的 synchronized 關鍵字來同步方法,因此在 Python 中要實現(xiàn)同步方法,通常我們是使用 threading.Lock() 來實現(xiàn)。在進入函數(shù)的地方獲取鎖,出函數(shù)的時候釋放鎖,這樣實現(xiàn)代碼看起好非常不好看。另外網上也有人給出了其它幾種實現(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)注解同步方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
- 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統(tǒng)計可散列的對象之容器Counter詳解
Counter是一個容器,可以跟蹤等效值增加的次數(shù).這個類可以用來實現(xiàn)其他語言中常用包或多集合數(shù)據結構實現(xiàn)的算法.本篇文章非常詳細的介紹了容器Counter的使用方式,需要的朋友可以參考下2021-05-05
Python 如何利用pandas 和 matplotlib繪制柱狀圖
Python 中的 pandas 和 matplotlib 庫提供了豐富的功能,可以幫助你輕松地繪制各種類型的圖表,本文將介紹如何使用這兩個庫,繪制一個店鋪銷售數(shù)量的柱狀圖,并添加各種元素,如數(shù)據標簽、圖例、網格線等,感興趣的朋友一起看看吧2023-10-10
淺談python中np.array的shape( ,)與( ,1)的區(qū)別
今天小編就為大家分享一篇python中np.array的shape ( ,)與( ,1)的區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

