我不明白为什么这种线程情况不起作用<线程锁不起作用>

时间:2019-08-23 09:30:03

标签: python multithreading concurrency thread-safety locking

我使用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。

1 个答案:

答案 0 :(得分:2)

我认为这是因为线程仍在运行。如果您尝试暂停一秒钟,则会显示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)