# -*- coding: utf-8 -*-
import threading
from functools import wraps
shared_resource_with_lock = 0
shared_resource_with_no_lock = 0
COUNT = 1000000
shared_resource_lock = threading.Lock()
def with_lock(l: threading.Lock):
"""
with_lock return a decorator to lock before op and unlock after op
"""
def wrapper(f):
# https://stackoverflow.com/questions/308999/what-does-functools-wraps-do
@wraps(f)
def inner(*args, **kw):
l.acquire()
try:
res = f(*args, **kw)
finally:
l.release()
return res
return inner
return wrapper
@with_lock(l=shared_resource_lock)
def add1():
global shared_resource_with_lock
shared_resource_with_lock += 1
@with_lock(l=shared_resource_lock)
def del1():
global shared_resource_with_lock
shared_resource_with_lock -= 1
def add_1():
global shared_resource_with_no_lock
shared_resource_with_no_lock += 1
def del_1():
global shared_resource_with_no_lock
shared_resource_with_no_lock -= 1
# 有锁的情况
def increment_with_lock():
for _ in range(COUNT):
add1()
def decrement_with_lock():
for _ in range(COUNT):
del1()
# 没有锁的情况
def increment_without_lock():
for _ in range(COUNT):
add_1()
def decrement_without_lock():
for _ in range(COUNT):
del_1()
if __name__ == "__main__":
t1 = threading.Thread(target=increment_with_lock)
t2 = threading.Thread(target=decrement_with_lock)
t3 = threading.Thread(target=increment_without_lock)
t4 = threading.Thread(target=decrement_without_lock)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print ("the value of shared variable with lock management is %s" % shared_resource_with_lock)
print ("the value of shared variable with race condition is %s" % shared_resource_with_no_lock)
网友评论