Python Bug 修复案例分析:多线程共享资源引发的数据不一致问题修复-修复过程​

时间:2025-05-09 07:29:12

为了解决多线程共享资源的数据不一致问题,我们需要使用同步机制来确保同一时刻只有一个线程能够访问和修改counter。在 Python 中,threading.Lock就是一种常用的同步工具。修改后的代码如下:

import threading

counter = 0
lock = threading.Lock()

def increment():
    global counter
    for _ in range(100000):
        with lock:
            counter += 1

threads = []
for _ in range(5):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("Counter value:", counter)

              在上述代码中,使用with lock:语句来获取锁,当一个线程进入这个代码块时,会获取到锁,其他线程就无法进入,只能等待锁被释放。这样就保证了在同一时刻只有一个线程能够对counter进行累加操作,避免了竞争条件,从而解决了数据不一致的问题。​

再次运行程序,输出结果为Counter value: 500000,符合程序的预期功能。​