我不明白为什么这种线程情况不起作用 <Thread lock doesn't work>

I cannot understand why this thread situation doesn't work <Thread lock doesn't work>

我使用了threading.Lock() 不是线程同时访问共享资源。但是,在我的代码案例中,它不起作用。

我知道不使用 Writer(在我的代码中),而是将此 class 作为函数,然后线程锁起作用并且结果为 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)