c++ 中的sleep 函数

来源:互联网 发布:陆小凤系列电影知乎 编辑:程序博客网 时间:2024/06/03 12:29

标准库中无该函数

但在某些编译系统中有,在有些系统库中有,要根据你那边的环境而定。如:

linux中有,unsigned int sleep(unsigned int seconds),传入挂起时间,成功返回0,不成功则返回余下的秒数。windows系统中有Sleep函数(注意大写),void Sleep(DWORD dwMilliseconds); 提供挂起的毫秒数。

例如:

#include<iostream>#include<windows.h>using namespace std;int main(){Sleep(3000);//暂停3秒  S要大写return 0;}

Use std::this_thread::sleep_for:

std::chrono::milliseconds timespan(111605); // or whateverstd::this_thread::sleep_for(timespan);

There is also the complimentary std::this_thread::sleep_until.


Prior to C++11, C++ had no thread concept and no sleep capability, so your solution was necessarily platform dependent. Here's a snippet that defines a sleep function for Windows or Unix:

#ifdef _WIN32    #include <windows.h>    void sleep(unsigned milliseconds)    {        Sleep(milliseconds);    }#else    #include <unistd.h>    void sleep(unsigned milliseconds)    {        usleep(milliseconds * 1000); // takes microseconds    }#endif
But a much simpler pre-C++11 method is to use boost::this_thread::sleep.