我使用 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。
我认为这是因为线程仍在运行。如果您尝试暂停一秒钟,则会打印 0。像这样:
import threading
import time
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()
time.sleep(1)
print(counter.count)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句