Python线程化sentinel值或事件来中断循环

2024-04-20 07:21:35 发布

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

我可以想出两种方法来打破Python线程中的循环,下面是最简单的例子:

1-使用sentinel值

from threading import Thread, Event
from time import sleep

class SimpleClass():

    def do_something(self):
        while self.sentinel:
            sleep(1)
            print('loop completed')

    def start_thread(self):
        self.sentinel = True
        self.th = Thread(target=self.do_something)
        self.th.start()

    def stop_thread(self):
        self.sentinel = False
        self.th.join()

simpleinstance = SimpleClass()
simpleinstance.start_thread()
sleep(5)
simpleinstance.stop_thread()

2-使用事件

^{pr2}$

在Python文档中,它讨论了事件,但没有讨论更简单的“sentinel-value”方法(我看到在许多关于堆栈溢出的线程问题的答案中都使用了这种方法)。

使用sentinel值有什么缺点吗?

具体地说,它是否会导致错误(我从来没有遇到过错误,但是我想如果你试图在while循环中读取sentinel的同时更改sentinel的值,那么某些东西可能会中断(或者在这种情况下,CPython GIL可以救我)。什么是最佳(最安全)实践?


Tags: 方法fromimportselfdefsleep线程do
1条回答
网友
1楼 · 发布于 2024-04-20 07:21:35

如果您查看Event的源代码,您会发现您正在使用的函数没有任何其他值:

class Event:
    def __init__(self):
        self._cond = Condition(Lock())
        self._flag = False

    def is_set(self):
        return self._flag

    def set(self):
        with self._cond:
            self._flag = True
            self._cond.notify_all() # No more-value, because you are not using Event.wait

所以在您的例子中,Event只是一个哨兵值的花哨包装,实际上没有实际用途,这也会使您的操作时间慢下来一小部分。在

事件只有在使用它们的wait方法时才有用。在

相关问题 更多 >