在C ++中的睡眠功能 [英] Sleep function in C++

查看:148
本文介绍了在C ++中的睡眠功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个函数,如 Sleep(time); 暂停程序X毫秒,但在C ++。

I need a function like Sleep(time); that pauses the program for X milliseconds, but in C++.

请写下要添加的标题和函数的签名。谢谢!

Please write which header to add and the function's signature. Thank you!

推荐答案

使用 std :: this_thread :: sleep_for

std::chrono::milliseconds timespan(111605); // or whatever

std::this_thread::sleep_for(timespan);

还有免费的 std :: this_thread :: sleep_until

在C ++ 11之前,C ++没有线程概念和睡眠功能,解决方案必然是平台依赖。以下是为Windows或Unix定义 sleep 函数的代码片段:

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

C ++ 11方法是使用 boost :: this_thread :: sleep

But a much simpler pre-C++11 method is to use boost::this_thread::sleep.

这篇关于在C ++中的睡眠功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆