带有事件对象的 Python 线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18485098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:52:08  来源:igfitidea点击:

Python Threading with Event object

pythonpython-multithreading

提问by user2724899

I've seen a lot of Python scripts that use Threads in a class and a lot of them use the threading.Event(). For example:

我见过很多在类中使用线程的 Python 脚本,其中很多都使用threading.Event(). 例如:

class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()

    def run(self):
        while not self.event.is_set():
            print "something"
            self.event.wait(120)

In the whileloop, why do they check the condition if they don't set self.event?

while循环中,如果他们没有设置,他们为什么要检查条件self.event

采纳答案by Viktor Kerkez

Because someone else will set it.

因为别人会设置它。

You generally start a thread in one part of your application and continue to do whatever you do:

您通常在应用程序的某个部分启动一个线程,然后继续执行您所做的任何操作:

thread = TimerClass()
thread.start()
# Do your stuff

The thread does it's stuff, while you do your stuff. If you want to terminate the thread you just call:

线程做它的东西,而你做你的东西。如果要终止线程,只需调用:

thread.event.set()

And the thread will stop.

线程将停止。

So the answer is: event, in this case, is not used for controlling the thread from inside the thread object itself. It is used for controlling the thread from outside (from the object which holds the reference to the thread).

所以答案是:在这种情况下,事件不用于从线程对象本身内部控制线程。它用于从外部(从持有对线程的引用的对象)控制线程。