简体   繁体   中英

C++ Wake up a sleeping thread?

There's a ton of questions and answers already ( Exhibit A ) about how to wake up a sleeping thread from another thread or how to have a thread sleep until it receives an instruction (same thing but described from another direction), but my question is more specifically about what is actually happening under the hood.

Is the only way to do this for the thread to itself choose to sleep and then check its queue, or some variable somewhere when it wakes, then sleep again?

Another method that I've seen mentioned is to use a mutex. Have the thread try to lock a locked mutex and it'll sleep then magically wake up when the mutex is unlocked by its original locker. But isn't that just doing the same thing under the hood? Ie going to sleep for x period of time then waking up at intervals to check if its still locked?

Is there any kind of wake functionality that doesn't require sleeping for set intervals? Like some kind of OS-level push? For example, the OS must be keeping track of when it needs to wake the sleeping thread, right? So in theory if you could change that number to 0 or 1 then it would wake up sooner. That makes sense.

The reason why I ask is because there's a tradeoff between how long it takes to wake up, and the amount of resources its using. The longer it sleeps between checks, the slower it is to respond, and the shorter it waits the more cycles it wastes checking something that another part of the application already knows has not changed. Seems inefficient.

You are misunderstanding condition variables. The thread in the first example in this answer will wake up after 1000 seconds or when the condition variable is notified . There is no tradeoff.

Likewise, a thread that waits for a mutex with a 1000-second timeout will wake up after 1000 seconds, or when the mutex is available and the thread acquires it .

You don't have to set low timeouts to get fast wakeups.

But isn't that just doing the same thing under the hood? Ie going to sleep for x period of time then waking up at intervals to check if its still locked?

No, it isn't. It tells the OS to wake it up whenever it's unlocked or after 1000 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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