系统:Ubuntu1804
在Jupyter Notebook中运行,使用的anaconda下的python3.7.6。
在代码运行中出现错误的问题,源代码如下:代码为书中样例代码,但是在运行时候并没有出现将value锁定的情况。
暂且记录下来,简单找了下没有找到答案,先记录下等日后再进行寻找。
class Counter(object):
def __init__(self):
self.count = 0
def increment(self, offset):
self.count += offset
class LockingCounter(object):
def __init__(self):
self.lock = Lock()
self.count = 0
def increment(self, offset):
with self.lock:
self.count += offset
def worker(sensor_index, how_many, counter):
for _ in range(how_many):
counter.increment(1)
def run_threads(func, how_many, counter):
threads = []
for i in range(5):
args = (i, how_many, counter)
thread = Thread(target=func, args=args)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
how_many = 10**5
counter = LockingCounter()
run_threads(worker, how_many, counter)
print("Counter should be %d, found %d" %(5*how_many, counter.count))
输出结果: