简体   繁体   English

使用Event对象进行Python线程处理

[英]Python Threading with Event object

I've seen a lot of Python scripts that use Threads in a class and a lot of them use the threading.Event() . 我见过很多在类中使用Threads的Python脚本,其中很多都使用threading.Event() For example: 例如:

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 while loop, why do they check the condition if they don't set self.event ? while循环中,为什​​么他们没有设置self.event检查条件?

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). 它用于从外部控制线程(从保存线程引用的对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM