【发布时间】:2019-12-28 14:38:11
【问题描述】:
我使用 threading.Lock() 不让线程同时访问共享资源。但是,在我的代码案例中,它不起作用。
我知道不是使用 Writer(在我的代码中),而是将这个类作为函数,然后线程锁起作用并且结果为 0。但我想知道为什么我的代码不起作用。这对我来说似乎是同样的情况。
import threading
global lock
lock = threading.Lock()
class Counter:
def __init__(self):
self.count = 0
def increment(self, offset):
self.count += offset
class Writer(object):
def __init__(self, counter: Counter):
self.counter = counter
def write(self, value):
with lock:
self.counter.increment(value)
if __name__ == "__main__":
counter = Counter()
def run(loop, value):
writer = Writer(counter)
for _ in range(loop):
writer.write(value)
t1 = threading.Thread(target=run, args=(100000, 1))
t2 = threading.Thread(target=run, args=(100000, -1))
t1.start()
t2.start()
print(counter.count)
我希望结果是 0。但不是 0。
【问题讨论】:
标签: python multithreading concurrency thread-safety locking