繁体   English   中英

C ++线程休眠而不冻结当前线程

[英]c++ thread sleep without freezing current thread

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

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

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 ++的菜鸟。

不要调用photos.join();

这将使您的主线程等待,直到照片线程结束。

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM