[英]Cross platform Sleep function for C++
是否可以使用宏制作跨平台睡眠代碼? 例如
#ifdef LINUX
#include <header_for_linux_sleep_function.h>
#endif
#ifdef WINDOWS
#include <header_for_windows_sleep_function.h>
#endif
...
Sleep(miliseconds);
...
#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
其中ms
是您想要休眠的時間(以毫秒為單位)。
您還可以將milliseconds
替換milliseconds
nanoseconds
、 microseconds
、 seconds
、 minutes
或hours
。 (這些是std::chrono::duration類型的特化。)
更新:在C++14 中,如果您睡眠了一定時間,例如 100 毫秒,則std::chrono::milliseconds(100)
可以寫為100ms
。 這是由於在C++11中引入的用戶定義文字。 在C++14 中, chrono
庫已擴展為包括以下用戶定義的文字:
std::literals::chrono_literals::operator""h
std::literals::chrono_literals::operator""min
std::literals::chrono_literals::operator""s
std::literals::chrono_literals::operator""ms
std::literals::chrono_literals::operator""us
std::literals::chrono_literals::operator""ns
實際上,這意味着您可以編寫這樣的內容。
#include <chrono>
#include <thread>
using namespace std::literals::chrono_literals;
std::this_thread::sleep_for(100ms);
請注意,雖然using namespace std::literals::chrono_literals
提供最少的命名空間污染,但在using namespace std::literals
或using namespace std::chrono
using namespace std::literals::chrono_literals
,這些運算符也可用。
就在這里。 您所做的是將不同的系統睡眠調用包裝在您自己的函數中以及如下所示的包含語句中:
#ifdef LINUX
#include <unistd.h>
#endif
#ifdef WINDOWS
#include <windows.h>
#endif
void mySleep(int sleepMs)
{
#ifdef LINUX
usleep(sleepMs * 1000); // usleep takes sleep time in us (1 millionth of a second)
#endif
#ifdef WINDOWS
Sleep(sleepMs);
#endif
}
然后您的代碼調用mySleep
進入睡眠狀態,而不是直接進行系統調用。
shf301 有一個好主意,但這種方式更好:
#ifdef _WINDOWS
#include <windows.h>
#else
#include <unistd.h>
#define Sleep(x) usleep((x)*1000)
#endif
然后像這樣使用:
Sleep(how_many_milliseconds);
得到提升。
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
...
boost::this_thread::sleep(boost::posix_time::millisec(milliseconds));
常用的解決方案是 select() 調用(需要 Winsock)。 此特定調用在 Linux 和 Windows 上具有完全相同的行為。
long value; /* time in microseconds */
struct timeval tv;
tv.tv_sec = value / 1000000;
tv.tv_usec = value % 1000000;
select(0, NULL, NULL, NULL, &tf);
在 linux 中記住 usleep 有一個限制。 你不能“睡覺”超過 1000 秒。
我會這樣寫
struct timespec req={0},rem={0};
req.tv_sec=(milisec/1000);
req.tv_nsec=(milisec - req.tv_sec*1000)*1000000;
nanosleep(&req,&rem);
從 C++ 11 開始,你就可以做到這一點。
#include<chrono>
#include<thread>
int main(){
std::this_thread::sleep_for(std::chrono::milliseconds(x));//sleeps for x milliseconds
std::this_thread::sleep_for(std::chrono::seconds(x));//sleeps for x seconds
std::this_thread::sleep_for(std::chrono::minutes(x));//sleeps for x minutes
std::this_thread::sleep_for(std::chrono::hours(x));//sleeps for x hours.
return 0;
}
我不知道當你能做到這一點時,你為什么要使用凌亂的宏,這種方法很棒,跨平台並且包含在 c++ 標准中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.