多线程中观察变量的Python方式?

2024-07-07 09:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

想象一下有两个线程observeTupTobserveT观察实例属性(instance.a)的值,如果其值为7,则应发出“警报”(在本例中打印注释)。然后是线程upT,它一次将实例属性的值增加1(instance.a+=1)

但是,由于随机选择的线程继续使用Python的Lock,我们无法确保观察者线程(observeT)捕捉到instance.a的值增加到7的时刻

如何确保每次upT释放锁后都调用观察者?请注意,保持线程upTobserveT分裂非常重要

有关详细信息,请参阅以下代码:

from threading import Lock, Thread


class MyClass():
    a: int

    def __new__(cls):
        instance = super().__new__(cls)
        instance.a = 0
        return instance

instance = MyClass()
lock = Lock()

def up():
    for i in range(100000):
        with lock:
            instance.a += 1

def observe():
    while True:
        with lock:
            a = instance.a
            if a == 7:
                print("This is 7!")
            if instance.a == 100000:
                break

observeT = Thread(target=observe)
upT = Thread(target=up)

observeT.start()
upT.start()

upT.join()
observeT.join()

谢谢你的帮助


Tags: 实例instancelocknew属性defmyclass线程
1条回答
网友
1楼 · 发布于 2024-07-07 09:19:32

这就是你要找的吗

from threading import Thread, Lock, Condition


class MyClass:
    def __init__(self, a_lock):
        self.cond = Condition(a_lock)
        self.canproceed = False
        self.a = 0

    def __setattr__(self, key, value):
        super().__setattr__(key, value)
        if key == 'a':
            if value == 7 or value == 100000:
                self.cond.notify()
                if value == 7:
                    while not self.canproceed:
                        self.cond.wait()


lock = Lock()
instance = MyClass(lock)


def up():
    for i in range(100000):
        with lock:
            instance.a += 1


def observe():
    with instance.cond:
        while instance.a != 7:
            instance.cond.wait()
        print("This is 7!")
        instance.canproceed = True
        instance.cond.notify()
        while instance.a != 100000:
            instance.cond.wait()




observeT = Thread(target=observe)
upT = Thread(target=up)

observeT.start()
upT.start()

upT.join()
observeT.join()

输出:

This is 7!

相关问题 更多 >