簡體   English   中英

我不明白為什么這種線程情況不起作用<Thread lock doesn't work>

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM