5

我有一个 C++11 程序来检查一个数字是否是素数。有一个程序等待准备好的未来对象。准备好后,程序会告诉未来对象的提供者函数是否认为该数是素数。

// future example
#include <iostream>       // std::cout
#include <future>         // std::async, std::future
#include <chrono>         // std::chrono::milliseconds


const int number = 4; // 444444443

// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
    for (int i=2; i<x; ++i) if (x%i==0) return false;
      return true;
    }

int main ()
{
    // call function asynchronously:
    std::future<bool> fut = std::async (is_prime, number); 

    // do something while waiting for function to set future:
    std::cout << "checking, please wait";
    std::chrono::milliseconds span (100);
    //std::chrono::duration<int> span (1);

    while (fut.wait_for(span)==std::future_status::timeout) {
        std::cout << '.';
        std::cout.flush();
    }

    bool x = fut.get();     // retrieve return value

    std::cout << "\n"<<number<<" " << (x?"is":"is not") << " prime.\n";

    return 0;
}

如果你运行程序,你会看到它处于一个无限的while循环中,因为wait_for()总是返回future_status::timeout,这意味着共享状态永远不会准备好。这是什么原因?我从http://www.cplusplus.com/reference/future/future/wait_for/ 获取了这个程序,所以我希望它能够工作。但是,如果我注释掉 while 循环,程序就会正常工作。

4

2 回答 2

11

代码正在运行:(g++ 4.9,clang 3.4)http://coliru.stacked-crooked.com/a/f3c2530c96591724

不过,我在使用 g++ 4.8.1 的 MINGW32 时得到了与您相同的行为。明确设置政策以std::launch::async解决问题。
(即std::async(std::launch::async, is_prime, number);:)

于 2014-06-19T07:50:28.740 回答
2

不确定这是否是编译器中的错误,但我相信 wait_for 应该返回future_status::deferred 这正是Scott Meyers 在他的书中所讨论 Effective C++Item 36:Specify std::launch::async if asynchronicity is essential

以及他提出的解决方案

解决方法很简单:只需检查调用对应的 futurestd::async以查看任务是否被延迟,如果是,则避免进入基于超时的循环。不幸的是,没有直接的方法来询问未来的任务是否被推迟。相反,您必须调用一个基于超时的函数——例如wait_for. 在这种情况下,你真的不想等待任何东西,你只是想看看返回值是否为std::future_status::deferred,所以在必要的迂回话中扼杀你的轻微怀疑并以零超时调用 wait_for 。

在您的情况下,您可以像@Jarod 在他的解决方案中提到的那样明确异步性,即使用std::launch::async或者您可以重写您的代码,如下所示

bool x;

// if task is deferred...
if (fut.wait_for(std::chrono::milliseconds(0)) == std::future_status::deferred)
{
  // ...use wait or get on fut
  // to call is_prime synchronously
  x = fut.get();     // retrieve return value
}
else
{
  // task isn't deferred
  // infinite loop not possible (assuming is_prime finishes)
  while (fut.wait_for(span) != std::future_status::ready) { 
    // task is neither deferred nor ready,
    // so do concurrent work until it's ready
    std::cout << '.';
    std::cout.flush();
  }

  // fut is ready
  x = fut.get();     // retrieve return value
}

测试一下

于 2017-07-24T21:01:27.857 回答