系统: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))
输出结果:

本文探讨了在Python多线程环境下,使用锁(lock)保护共享资源的重要性。通过一个计数器类的实例,展示了如何避免竞态条件(race condition),确保线程安全。在代码示例中,对比了未加锁和加锁的计数器实现,强调了正确同步机制对于并发编程的必要性。

1491

被折叠的 条评论
为什么被折叠?



