2010-11-24 180 views
34

似乎不可能睡覺使用boost :: thread的線程。 方法睡眠需要system_time,但我該如何構建它?如何睡覺一個C++ Boost線程

尋找內庫並不能真正幫助很大......

基本上我有我傳遞給這個線程作爲入口點函數中的一個線程 ,我想打電話給像

boost::this_thread::sleep 

什麼的,該怎麼做?

謝謝

回答

83

根據您的Boost版本:

要麼...

#include <boost/chrono.hpp> 
#include <boost/thread/thread.hpp> 

boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); 

或者......

#include <boost/date_time/posix_time/posix_time.hpp> 
#include <boost/thread/thread.hpp> 

boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 

您還可以使用微秒,秒,幾分鐘,幾小時,也許還有一些,我不確定。

+2

是的,謝謝你...我沒有注意使用this_thread,但只是提升::線程和沒有工作:) Thansk – Andry 2010-11-24 13:37:47

+2

這給了我以下錯誤(使用Xcode 5/LLVM):錯誤:沒有可行的轉換從'boost :: posix_time :: microseconds'(又名'subsecond_duration ')到'const system_time'(又名'const boost :: posix_time :: ptime') – 2014-01-31 11:38:15

3

首先

boost::posix_time::seconds secTime(1); 
boost::this_thread::sleep(secTime); 

其次

boost::this_thread::sleep(boost::posix_time::milliseconds(100)); 
19

從另一篇文章,我學到boost::this_thread::sleep已經廢棄了升壓V1.5.3:http://www.boost.org/doc/libs/1_53_0/doc/html/thread/thread_management.html

相反,嘗試

void sleep_for(const chrono::duration<Rep, Period>& rel_time); 

例如

boost::this_thread::sleep_for(boost::chrono::seconds(60)); 

也許嘗試

void sleep_until(const chrono::time_point<Clock, Duration>& abs_time); 

我使用升壓V1.53與過時sleep功能,並不定期地崩潰的程序。當我將sleep函數的調用更改爲調用sleep_for函數時,程序停止崩潰。

0

我學到了艱辛的道路,至少在MS Visual Studio中(試過2013年和2015年)有

boost::this_thread::sleep(boost::posix_time::microseconds(SmallIterval)); 

boost::this_thread::sleep_for(boost::chrono::microseconds(SmallIterval)); 
or 
std::this_thread::sleep_for(std::chrono::microseconds(SmallIterval)); 

當間隔小於一些比較小的之間的巨大差異實質性的門檻(我看到15000微秒的閾值= 15毫秒)。

如果SmallIterval很小,sleep()會立即中斷。睡眠(100 mks)表現爲睡眠(0 mks)。

但是,小於閾值的時間間隔的sleep_for()在整個閾值內暫停。 sleep_for(100 mks)表現爲sleep_for(15000 mks)。

間隔大於閾值和值爲0的行爲是相同的。