让线程等待计时器还是信号? [英] Make a thread wait for either a Timer or a Signal?

查看:132
本文介绍了让线程等待计时器还是信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个多线程Python应用程序,在以下情况下每个线程都应唤醒:

I am writing a Multithreaded Python application, in which each thread should wake up under the following circumstances:

  1. 来自主线程的信号
  2. 计时器调用本身开始

换句话说,线程应该根据自己设置的计时器唤醒,并且每当出现相关事件时,都能够响应来自管理线程的信号.

In other words, threads should wake up according to a timer they set for themselves, and be able to respond to a signal from a managing thread whenever a relevant event appears.

实现双重(计时器/事件)唤醒机制的惯用方式是什么?

What's the idiomatic way to implement a dual (Timer/Event) wake-up mechanism?

推荐答案

好吧,等待方法,需要超时.因此,您可以做些像

Well, threading.Event, has a wait method, which takes a timeout. So you could do something as simple as

在主线程中:

sleepEvent = threading.Event()

将其传递给您的其他线程,并放入其中:

pass that to your other threads, and in them:

sleepEvent.wait(10) # wait for up to 10 seconds

现在您的线程将等待10秒(如计时器),或者在主线程调用时清除等待时间

Now your thread will either wait 10 seconds (like a timer) or will clear the wait if the main thread calls

sleepEvent.set()

这篇关于让线程等待计时器还是信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆