C++ 如何 std::thread 睡眠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12859548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to std::thread sleep
提问by José
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::thread 的新手。我需要让一个线程从另一个线程休眠,这可能吗?在示例中,我看到的只是如下代码:
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));
或者
sleep(t, std::chrono::seconds(1));
Any ideas?
有任何想法吗?
回答by tenfour
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
.
因为sleep_for
是同步的,所以只有在当前线程中才真正有意义。您想要的是一种暂停/恢复其他线程的方法。该标准没有提供执行此操作的方法(afaik),但您可以使用依赖于平台的方法使用native_handle
.
For example on Windows, SuspendThread
and ResumeThread
.
例如在 Windows 上,SuspendThread
和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.
但更重要的是,几乎从不需要这样做。通常,当您遇到标准没有提供的基本需求时,这是一个危险信号,表明您正朝着危险的设计道路前进。考虑以不同的方式实现更大的目标。
回答by Zeta
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.
不可以。您必须提供一个同步接口,这会抵消线程带来的性能提升。唯一具有是否可以休眠所需信息的线程是线程本身。因此std::thread
没有成员sleep
,而std::this_thread
有一个。