José José - 1 month ago 22
C++ Question

How to std::thread sleep

I new to use std::thread, I wan't to be able 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?

Answer

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.