python實現synchronized

利用python的裝飾器實現類似java中的synchronized

from threading import Lock,Thread
from functools import wraps

default_lock=Lock()
lock_list={'default':Lock()}
def synchronized(func=None,obj=None):
    if func is not  None:
        @wraps(func)
        def wrapper(*args,**kwargs):
            lock=lock_list['default']
            lock.acquire()
            try:
                return func(*args,**kwargs)
            finally:
                lock.release()
        return wrapper
    if obj is not None:
        cur_id=id(obj)
        default_lock.acquire()
        try:
            current_lock=lock_list.get(id(obj),None)
            if current_lock is None:
                current_lock=Lock()
                lock_list[cur_id]=current_lock
        finally:
            default_lock.release()
        def decorator(func):
            def wrapper(*args,**kwargs):
                current_lock.acquire()
                try:
                    return func(*args,**kwargs)
                finally:
                    current_lock.release()
            return wrapper
        return decorator


a=0
obj=[]
@synchronized(obj=obj)
def add():
    global a
    a+=1
@synchronized(obj=obj)
def sub():
    global a
    a-=1
'''
使用兩把鎖會出現錯誤的原因是由於可以同時有兩個線程修改a,但是同一把鎖就不行,因爲這把鎖不釋放其他線程就不能操作a
'''
def task():
    for i in range(6672325):
        sub()
        add()

thread_list=[Thread(target=task) for i in range(4)]
[t.start() for t in thread_list]
[t.join() for t in thread_list]
print(a)


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章