C++ boost::thread sleep() 有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1974166/
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
What does boost::thread sleep() do?
提问by user240137
I am currently working on a small wrapper class for boost thread but I dont really get how the sleep function works, this is what I have got so far:
我目前正在为 boost 线程开发一个小包装类,但我真的不明白 sleep 函数是如何工作的,这是我到目前为止所得到的:
BaseThread::BaseThread(){
thread = boost::thread();
bIsActive = true;
}
BaseThread::~BaseThread(){
join();
}
void BaseThread::join(){
thread.join();
}
void BaseThread::sleep(uint32 _msecs){
if(bIsActive)
boost::this_thread::sleep(boost::posix_time::milliseconds(_msecs));
}
This is how I implemented it so far but I dont really understand how the static this_thread::sleep method knows which thread to sleep if for example multiple instances of my thread wrapper are active. Is this the right way to implement it?
这是我到目前为止实现它的方式,但我真的不明白静态 this_thread::sleep 方法如何知道如果我的线程包装器的多个实例处于活动状态,那么哪个线程要休眠。这是实现它的正确方法吗?
回答by Klaim
boost::this_thread::sleepwill sleep the current thread. Only the thread itself can get to sleep. If you want to make a thread sleep, add some check code in the thread or use interruptions.
boost::this_thread::sleep将使当前线程休眠。只有线程本身可以进入睡眠状态。如果要让线程休眠,请在线程中添加一些检查代码或使用 interrupts。
UPDATE: if you use a c++11 compiler with the up to date standard library, you'll have access to std::this_thread::sleep_forand std::this_thread::sleep_untilfunctions. However, there is no standard interruption mechanism.
更新:如果您使用带有最新标准库的 c++11 编译器,您将可以访问std::this_thread::sleep_for和std::this_thread::sleep_until函数。但是,没有标准的中断机制。
回答by Beno?t
sleep always affects current thread (the one that calls the method).
sleep 总是影响当前线程(调用该方法的线程)。