在C ++应用程序后面运行的C ++ Timer

时间:2012-08-19 15:35:05

标签: c++ c++11 ubuntu-12.04

我有一个在前台运行的C ++应用程序。我需要一个与应用程序同时运行的计时器。当计时器到达零时,我需要计时器弹出一个窗口。

我无法使用sleep(),因为who应用程序会休眠。请告知如何做到这一点。

2 个答案:

答案 0 :(得分:10)

由于您使用的是C ++ 11,我建议您使用thread library

您可能想要的是std::this_thread::sleep_forstd::this_thread::sleep_until,可以在您的计时器线程的上下文中调用。

像这样......

std::thread timer([]() {
  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "hello, world!" << std::endl;
});
std::cout << "thread begun..." << std::endl;
timer.join();

答案 1 :(得分:0)

我建议下载Boost库,然后使用this非常简单的教程创建一个boost线程。

如果您不想花时间下载/安装/配置Boost,请使用Windows threads。 (我假设您正在尝试使用Windows上的sleep())。但是,Windows线程比Boost线程更难理解。

在实际程序中,你需要包含这样的东西(以Boost为例):

void timer() {

    sleep(x);
    //Whatever code here to make your popup window.
    return NULL;
}

int main() {

    boost::thread prgmTimer(&timer);
    //Regular code here.
    //prgmTimer.join(); //Remove the comment on that command if you want something to
                        //to happen after your timer runs down and only if your
                        //timer runs down. (Ex. the program exits).
    return 0;
}