【问题标题】:I cannot understand why this thread situation doesn't work <Thread lock doesn't work>我不明白为什么这种线程情况不起作用 <Thread lock doesn't work>
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 很高兴有帮助! :)
    猜你喜欢
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2017-11-26
    • 2010-12-29
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多