Python 我无法理解为什么这个线程情况没有';t工作<;螺纹锁紧不';t work>;

Python 我无法理解为什么这个线程情况没有';t工作<;螺纹锁紧不';t work>;,python,multithreading,concurrency,thread-safety,locking,Python,Multithreading,Concurrency,Thread Safety,Locking,我使用threading.Lock()不允许线程同时访问共享资源。但是,在我的代码中,它不起作用 我知道不使用Writer(在我的代码中),而是将这个类作为函数,然后线程锁工作,结果是0。但我想知道为什么我的代码不起作用。对我来说情况似乎也一样 导入线程 全局锁 lock=threading.lock() 班级柜台: 定义初始化(自): self.count=0 def增量(自补偿): self.count+=偏移量 类编写器(对象): 定义初始化(自身,计数器:计数器): self.count

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

我知道不使用Writer(在我的代码中),而是将这个类作为函数,然后线程锁工作,结果是0。但我想知道为什么我的代码不起作用。对我来说情况似乎也一样

导入线程
全局锁
lock=threading.lock()
班级柜台:
定义初始化(自):
self.count=0
def增量(自补偿):
self.count+=偏移量
类编写器(对象):
定义初始化(自身,计数器:计数器):
self.counter=计数器
def写入(自身、值):
带锁:
自我计数器增量(值)
如果名称=“\uuuuu main\uuuuuuuu”:
计数器=计数器()
def运行(循环,值):
写入器=写入器(计数器)
对于范围内的(循环):
writer.write(值)
t1=线程。线程(目标=运行,参数=(100000,1))
t2=线程。线程(目标=运行,参数=(100000,-1))
t1.start()
t2.start()
打印(计数器计数)

我希望结果是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)

我想这是因为线程还在运行。如果您尝试暂停一秒钟,它将打印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)

很高兴这有帮助!:)很高兴这有帮助!:)