【问题标题】:c++ thread sleep without freezing current threadc++线程休眠而不冻结当前线程
【发布时间】:2013-09-02 15:47:13
【问题描述】:

我正在编写一个应用程序,我需要在不停止执行当前线程的情况下让新线程休眠。

来自应用程序的一些代码:

PlaySound(L"sounds\\started.wav", NULL, SND_FILENAME);
thread photos(makeScreens);
photos.join();
CONSOLE_Print("Some testing string");

以及应该异步工作的函数:

void makeScreens(){
    CONSOLE_Print("Make Screens entered");
    srand (time(NULL));
    CONSOLE_Print("Sleeping 30s");
    Sleep(30000);
    CONSOLE_Print("Wake up");
    long int delay;
    for(int i=0; i<5; i++){ //loop for max screens=5
        delay=rand() % 600000 + 60000; //random a delay beetween sreens from 1 to 10 minutes
        CONSOLE_Print("Sleeping "+delay/1000);
        Sleep(delay); //sleep 
        CONSOLE_Print("Wake up and make screen");
        gdiscreen(i); //take a screen
    }
}

所以我想在不停止当前执行应用程序的情况下运行 makescreens()。我的输出应该是这样的:

Some testing string
Make Screens entered
Sleeping 30s
Wake up
Sleeping xxxx
Wake up and make screen

如何解决?除了使用睡眠之外,还有其他方法吗?我是 C++ 的新手。

【问题讨论】:

  • Sleep 的重点是冻结当前线程,所以你的问题没有多大意义。

标签: c++ multithreading asynchronous sleep


【解决方案1】:

不要打电话给photos.join();

这将使您的主线程等待照片线程完成。

【讨论】:

  • 那么如何在不等到结束的情况下调用它呢?
  • 试试 photos.detach();但是你必须确保主线程一直运行到你的照片线程完成,否则它会在它完成之前被杀死。
【解决方案2】:

join 表示主线程(启动新线程)等待启动的线程完成后再继续。所以下面的订购应该满足您的印刷订单要求。

PlaySound(L"sounds\\started.wav", NULL, SND_FILENAME);
CONSOLE_Print("Some testing string");
thread photos(makeScreens);
photos.join();
CONSOLE_Print("new thread has now finished running");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多