2013-03-02 31 views
0

我正在用C++编写一些东西,其中包括一个倒计时函数,它在达到0时设置一个值。我一直在研究线程/ pthreads/boost线程几个小时,我似乎无法得到任何工作,所以我理想的是寻找需要用我的代码做什么的演练。我对C++相当陌生,但不管语言如何,并发性都超出了我以前看过的任何内容。在后台运行函数直到完成MinGW + Windows

我想在后台运行的功能是:

void Counter::decrementTime(int seconds){ 
    while(seconds != 0){ 
     seconds--; 
     Sleep(1000); 
    } 
    bool = false; 
} 

它将通过为简单的东西可以被称为(这只是举例):

void Counter::setStatus(string status){ 
    if(status == "true"){ 
     bool = true; 
     decrementTime(time); // Needs to run in background. 
    } else if (status != "false"){ 
     bool = false; 
    } 
} 

我已经尝试了各种各样的东西,如std:thread myThread(decrementTime, time);以及其他各种尝试(所有标题正确包括等)。

如果有人能帮助我,我会很感激。我不需要监视正在运行的函数或任何其他的东西,我需要的就是在它到达时设置bool。我使用启用了-std=c++11的MinGW编译器运行Windows,正如我前面提到的,我很乐意解决这个问题(并解释了它是如何解决的),所以我可以更好地理解这个概念!

哦,如果有没有线程的替代(更好)的方式来做到这一点,请随时分享您的知识!

+0

请详细说明你准备尝试完成的事情,请在“if(status ==”true“)... else if(status!=”false“)等条件下解释你的逻辑......” – 2013-03-02 00:39:27

+0

@AndyT那不是它会是什么,这仅仅是为了举例。我想继续做不同的事情,而'seconds'在后台倒数到0。意思是我可以在别处使用'while(!bool)'。 – whitfin 2013-03-02 00:45:39

回答

1

你可以使用一个std::atomic_bool为标志,并std::async推出时间在一个单独的线程:

#include <atomic> 
#include <chrono> 
#include <future> 

std::atomic_bool flag{true}; 

void countDown(int seconds){ 
    while(seconds > 0){ 
    seconds--; 
    std::this_thread::sleep_for(std::chrono::miliseconds(??)); // 
    } 
    flag = false; 
} 

auto f = std::async(std::launch::async, std::bind(countDown, time)); 

// do your work here, checking on flag 
while (!flag) { ... } 

f.wait(); // join async thread 
+0

有什么我必须做的才能使async可用?这些标题似乎不适合我。 – whitfin 2013-03-02 15:44:13

+0

@ Zackehh9lives它应该在''标题中。这可能是因为你没有所需的C++ 11。您也可以在'std :: thread'中启动并在末尾调用'thread.join()'。 – juanchopanza 2013-03-03 08:45:23

+1

即使我使用C++ 11,这也是MinGW中的一个问题,但我已经对它进行了修补,现在它正在工作,谢谢! – whitfin 2013-03-03 13:01:37

1

您可以使用std ::异步和std::future及其方法“wait_for” 0超时

+0

我将如何运行'decrementTime()'使用异步? – whitfin 2013-03-02 00:57:08

+0

std :: async(std :: launch :: async,std :: bind(decreentTime,time))。但是想法是,yu不需要任何共享的bool变量,您可以使用返回的std :: future并查询它是否已完成 – 2013-03-02 03:45:42