【问题标题】:C++ std::async encounters system_error?C++ std::async 遇到 system_error?
【发布时间】:2017-12-08 03:45:06
【问题描述】:

我在这里尝试了 std:async 示例代码 http://www.cplusplus.com/reference/future/async/

但是,我遇到了未知错误 -1 的系统错误。任何人都可以帮助我吗?谢谢!

以下是我从网站复制的代码:

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

// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
  std::cout << "Calculating. Please, wait...\n";
  for (int i=2; i<x; ++i) if (x%i==0) return false;
  return true;
}

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

  std::cout << "Checking whether 313222313 is prime.\n";
  // ...

  bool ret = fut.get();      // waits for is_prime to return

  if (ret) std::cout << "It is prime!\n";
  else std::cout << "It is not prime.\n";

  return 0;
}

以下是我的命令行:

ubuntu:~/cpp_dynamic_invoke_success/stdasync_test$ g++ isprime.cpp -std=c++11 -o isprime
ubuntu:~/cpp_dynamic_invoke_success/stdasync_test$ ./isprime 
Checking whether 313222313 is prime.
terminate called after throwing an instance of 'std::system_error'
  what():  Unknown error -1
Aborted (core dumped)

我的ubuntu版本:

No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.3 LTS
Release:    14.04
Codename:   trusty

还有g++版本。

g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

【问题讨论】:

  • 虽然没有答案,但这是this question的骗子
  • 这是一个相当旧的 GCC 版本,因此您可能需要在编译命令的末尾添加 -pthread 标志。
  • 谢谢!添加-pthread 真的很有帮助!

标签: c++ c++11 asynchronous gcc


【解决方案1】:

答案是在编译选项后添加-pthread

g++ isprime.cpp -std=c++11 -o isprime -pthread

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多