简体   繁体   English

在特定时间后唤醒线程

[英]Wake up a thread after a specific time

I have two threads, say 1 and 2, and have put 2 to sleep. 我有两个线程,例如1和2,并且已经让2进入睡眠状态。 1 performs some task and sets a timer to wake up 2 't' seconds after the task is done. 1执行一些任务,并将计时器设置为在任务完成后的2 t秒钟内唤醒。

So, I need to program to send a signal to 2 't' seconds later. 因此,我需要编程以在2秒钟后发送信号。 How can I achieve this? 我该如何实现?

You can use a timed-wait on a condition variable, which will wake up when that time is reached / has elapsed. 您可以在条件变量上使用定时等待,当达到/经过该时间时,它将唤醒。 You can also just make a thread sleep for a period of time. 您也可以使线程休眠一段时间。

pthreads (which you specify) only has a wait until an absolute time. pthreads(您指定的)只能等待绝对时间。

The new standard C++ library and boost give you the option of wait_for(time_period) or wait_until(absolute_time) . 新的标准C ++库和boost使您可以选择wait_for(time_period)wait_until(absolute_time)

In your case I don't think you need to do any of this but you might use a 3rd thread. 就您而言,我认为您不需要执行任何此操作,但是您可以使用第3个线程。

  1. Thread 1 performs the task, Thread 2 waits on a condition variable, when thread 1 completes the task it creates a 3rd thread which sleeps and wakes thread 2. 线程1执行任务,线程2等待条件变量,当线程1完成任务时,它将创建第3个线程,该线程休眠并唤醒线程2。

  2. Thread 1 performs the task and immediately signals the condition variable held by thread 2, but thread 2 then sleeps before it continues. 线程1执行该任务,并立即发出信号通知线程2持有的条件变量,但是线程2随后进入睡眠状态,然后继续。 (So really it wakes up earlier but it simulates the delay). (因此实际上它会更早地唤醒,但它模拟了延迟)。 No need for a 3rd thread, However thread 2 might be a "client" thread and you want to enforce the delay so use method 1 if that is the case. 不需要第三线程,但是线程2可能是“客户端”线程,并且您想强制执行延迟,因此,请使用方法1。

Prior than C++11, the standard library did not offer timers. 在C ++ 11之前,标准库不提供计时器。 Even with C++11, you have standrd timing facilities (eg, sleep, condition variables, etc.) but you have to assemble them to have the desired behavior. 即使使用C ++ 11,您也具有标准的计时功能(例如,睡眠,条件变量等),但必须将它们组合起来才能具有所需的行为。

So, you roughly have the following otions: 因此,您大致有以下几点:

  • rely on some specific (cross-platform) library (eg, Qt, Boost, etc.) 依赖于某些特定的(跨平台)库(例如Qt,Boost等)
  • rely on OS-level facilities (eg, Posix on Linux) 依赖于操作系统级别的设施(例如,Linux上的Posix)
  • create a third thread acting as timer: once activated, it sleeps for 2 seconds and then signals the second thread through a condition variable 创建第三个线程充当计时器:一旦激活,它将休眠2秒钟,然后通过条件变量向第二个线程发出信号
  • let the first thread compute the amount of time to wait after the work done, make it sleep and then signal the other thread through a condition variable 让第一个线程计算完成工作后要等待的时间,使其进入休眠状态,然后通过条件变量向另一个线程发出信号

I suggest the last option. 我建议最后一个选择。

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

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