José José - 4 months ago 68
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:


But what I want to do is something like:

std::thread t([]{...});

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

Any ideas?


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.