我知道POSIX休眠(x)函数使程序休眠x秒。C++中是否有一个函数可以让程序休眠x毫秒?
当前回答
#include <windows.h>
语法:
Sleep ( __in DWORD dwMilliseconds );
用法:
Sleep (1000); //Sleeps for 1000 ms or 1 sec
其他回答
使用Boost异步输入/输出线程,休眠x毫秒;
#include <boost/thread.hpp>
#include <boost/asio.hpp>
boost::thread::sleep(boost::get_system_time() + boost::posix_time::millisec(1000));
注意,没有毫秒的标准C API,因此(在Unix上)您必须接受usleep,它接受微秒:
#include <unistd.h>
unsigned int microseconds;
...
usleep(microseconds);
在具有选择功能的平台(POSIX、Linux和Windows)上,您可以执行以下操作:
void sleep(unsigned long msec) {
timeval delay = {msec / 1000, msec % 1000 * 1000};
int rc = ::select(0, NULL, NULL, NULL, &delay);
if(-1 == rc) {
// Handle signals by continuing to sleep or return immediately.
}
}
然而,现在有更好的选择。
为了保持便携性,您可以使用Boost::Thread进行睡眠:
#include <boost/thread/thread.hpp>
int main()
{
//waits 2 seconds
boost::this_thread::sleep( boost::posix_time::seconds(1) );
boost::this_thread::sleep( boost::posix_time::milliseconds(1000) );
return 0;
}
此答案是重复的,以前已在该问题中发布过。也许你也可以在那里找到一些有用的答案。
为什么不使用time.h库?在Windows和POSIX系统上运行(不要在生产中使用此代码!):
CPU保持空闲状态:
#include <iostream>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif // _WIN32
using namespace std;
void sleepcp(int milliseconds);
void sleepcp(int milliseconds) // Cross-platform sleep function
{
#ifdef _WIN32
Sleep(milliseconds);
#else
usleep(milliseconds * 1000);
#endif // _WIN32
}
int main()
{
cout << "Hi! At the count to 3, I'll die! :)" << endl;
sleepcp(3000);
cout << "urrrrggghhhh!" << endl;
}
推荐文章
- 如何有效地清除std::queue ?
- 在哪种情况下我使用特定的STL容器?
- Uint8_t不能用cout打印
- 使用sudo时未找到命令
- c++中不必要的花括号
- 如何反转一个c++向量?
- 当有命令行参数时,如何使用GDB分析程序的核心转储文件?
- 如何开始开发Internet Explorer扩展?
- Std::auto_ptr改为Std::unique_ptr
- int的最大值
- c++中有最大数组长度限制吗?
- 如何强制从另一个SSH会话分离屏幕?
- 什么是“参数依赖查找”(又名ADL,或“Koenig查找”)?
- 公共朋友交换成员函数
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?