【问题标题】:Running function in background until completion MinGW + Windows在后台运行功能直到完成 MinGW + Windows
【发布时间】:2013-03-02 00:29:14
【问题描述】:

我正在用 C++ 编写一些东西,其中包括一个倒计时函数,该函数在它达到 0 时设置一个值。我已经研究线程/pthreads/boost 线程几个小时了,但我似乎什么也得不到工作,所以我理想情况下正在寻找需要对我的代码做什么的演练。我对 C++ 还很陌生,但是无论语言如何,并发性都超出了我以前研究过的任何东西。

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

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,正如我之前提到的,我很想解决这个问题(并解释了它是如何解决的),这样我就可以更好地掌握这个概念!

哦,如果有其他(更好的)方法可以在没有线程的情况下执行此操作,也请随时分享您的知识!

【问题讨论】:

  • 请详细说明您到底想完成什么,还请解释您在“if (status == "true") ... else if (status != "false") .. 。”
  • @AndyT 这不是它的样子,这只是为了举例。我想继续做不同的事情,而seconds 在后台倒计时到 0。这意味着我可以在其他地方使用while (!bool)

标签: c++ windows multithreading c++11 mingw


【解决方案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

【讨论】:

  • 我必须做些什么才能使异步可用吗?这些标题似乎不适合我。
  • @Zackehh9lives 它应该在 &lt;future&gt; 标头中。可能是您没有所需的 C++11。您也可以在std::thread 中启动并在最后调用thread.join()
  • 即使我有 C++11,这也是 MinGW 中的一个问题,但我已经对其进行了修补,它现在可以工作了,谢谢!
【解决方案2】:

您可以使用 std::async 和 std::future 及其方法“wait_for”,超时时间为 0

【讨论】:

  • 如何使用异步运行decrementTime()
  • std::async(std::launch::async, std::bind(decreentTime, time))。但想法是你不需要任何共享的布尔变量,你可以使用返回的 std::future 并查询它是否完成
猜你喜欢
  • 1970-01-01
  • 2010-12-28
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
相关资源
最近更新 更多