Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to std::thread sleep

I am new to std::thread. I need to put a thread to sleep from another thread, is that possible? In examples, all I see is code like:

std::this_thread::sleep_for(std::chrono::seconds(1));

But what I want to do is something like:

std::thread t([]{...});
t.sleep(std::chrono::seconds(1));

or sleep(t, std::chrono::seconds(1));

Any ideas?

like image 306
José Avatar asked Oct 12 '12 12:10

José


People also ask

How do you make a thread sleep in C++?

C++ 11 provides specific functions to put a thread to sleep. Description: The sleep_for () function is defined in the header <thread>. The sleep_for () function blocks the execution of the current thread at least for the specified time i.e. sleep_duration.

How do you wake up a STD thread while it's asleep?

You can use std::promise/std::future as a simpler alternative to a bool / condition_variable / mutex in this case. A future is not susceptible to spurious wakes and doesn't require a mutex for synchronisation.

What is std :: This_thread?

std::this_threadThis namespace groups a set of functions that access the current thread.


2 Answers

Because sleep_for is synchronous, it only really makes sense in the current thread. What you want is a way to suspend / resume other threads. The standard does not provide a way to do this (afaik), but you can use platform-dependent methods using native_handle.

For example on Windows, SuspendThread and ResumeThread.

But more important is that there is almost never a need to do this. Usually when you encounter basic things you need that the standard doesn't provide, it's a red flag that you're heading down a dangerous design path. Consider accomplishing your bigger goal in a different way.

like image 183
tenfour Avatar answered Sep 21 '22 03:09

tenfour


No. The standard doesn't give you such a facility, and it shouldn't. What does sleep do? It pauses the execution of a given thread for a at least the given amount of time. Can other threads possibly know without synchronizing that the given thread can be put to sleep in order to achieve a better performance?

No. You would have to provide an synchronized interface, which would counter the performance gain from threads. The only thread which has the needed information whether it's ok to sleep is the thread itself. Therefore std::thread has no member sleep, while std::this_thread has one.

like image 27
Zeta Avatar answered Sep 21 '22 03:09

Zeta