简体   繁体   English

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

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

I have writing an application an I need to sleep new thread without stopping executing of current one. 我正在编写一个应用程序,我需要在不停止当前线程执行的情况下休眠新线程。

Some code from application: 来自应用程序的一些代码:

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

And function that should work asynchronous: 和应该异步工作的功能:

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
    }
}

So I want to run makescreens() without stopping current execution of app. 所以我想运行makescreens()而不停止当前执行的应用程序。 My output should be like this: 我的输出应该是这样的:

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

How to fix it? 如何解决? Is there any other way instead of using sleep? 还有其他方法可以代替睡眠吗? I'm nawbie in c++. 我是C ++的菜鸟。

Don't call photos.join(); 不要调用photos.join(); .

This will make your main thread wait until the photo thread is finished. 这将使您的主线程等待,直到照片线程结束。

join means that the main thread (which launched new thread) waits for launched thread to finish before proceeding. join表示主线程(已启动新线程)在继续之前等待启动线程完成。 So the ordering below should meet your printing order requirement. 因此,以下订购应满足您的印刷订单要求。

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