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

特里·乔

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我不明白为什么for循环不起作用

不明白为什么 raycast 代码不起作用

我不明白为什么我的.find函数不起作用

我不明白为什么我的 Athena (Presto) SQL 查询不起作用

我不明白为什么我的石头,剪刀布游戏中的得分不起作用

我不明白为什么我的计算不起作用

我不明白为什么我的代码的“再玩”药水不起作用

不明白为什么我的异步等待在我的 lambda 函数中不起作用

dplyr 中的多于/少于函数不起作用(或者我不明白为什么它们不起作用)

不明白为什么我的 php 余弦相似度代码不起作用

我不明白为什么这个查询不起作用

我不明白为什么这个 Array 不起作用?

Java:我不明白为什么这不起作用

从数据库中删除的实现不起作用,我不明白为什么

全局语句不起作用,我不明白为什么

JQuery、PHP 和 mySQL 帮助。我不明白为什么这不起作用

我不明白为什么cordova 链接和Javascript 编码不起作用

我不明白为什么在我的代码中使用“”会起作用,但是与“”相同的代码却不起作用

Python 的线程和多进程锁不起作用

为什么线程不起作用?

不明白为什么数字和代码不起作用

as3 hittestobject不起作用,不明白为什么

BubbleSort线程不起作用

我的创建语音通道命令不起作用,我不明白为什么它不能识别“执行”,我该如何解决?

你能帮我找出这段代码中的错误吗?我似乎不明白为什么它不起作用?

我遇到一个奇怪的问题,使用NOT IN对PostgreSQL数据库运行查询,并且不明白为什么它不起作用

我不明白为什么一个代码可以工作而另一个代码不起作用

我不明白为什么带options_from_collection_for_select的f.select的Ruby on Rails代码不起作用

我不明白为什么 python 中的 googletrans 不起作用,它给出错误:AttributeError: 'NoneType' object has no attribute 'group'