std::future and "Unknown error -1"

Running this example from the documentation gives me an error:

Checking whether 313222313 is prime.
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
Aborted (core dumped)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 // 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;
}


Does anyone know why? I am using G++ and 4.8.1

/Johan
if you're using gcc, you must pass the compiler option -pthread to use threading:

~ $ g++ -Wall -Wextra -pedantic-errors -O3 -std=c++11 -pthread -o test test.cc
~ $ ./test
Checking whether 313222313 is prime.
Calculating. Please, wait...
It is prime!

$ g++ -Wall -Wextra -pedantic-errors -O3 -std=c++11 -pthread -o astest astest.cc
$ ./astest
Checking whether 313222313 is prime.
terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1


I'm not sure what I am missing. Forgetting -pthread will give me a different error, not "Unknown error -1"
hm.. on coliru, with gcc-4.8, forgetting -pthread gives exactly " what(): Unknown error -1": http://coliru.stacked-crooked.com/a/123e54ea87053b40 and with it the program runs as expected: http://coliru.stacked-crooked.com/a/e0aaeb00788a8f62
this starts to look like a compiler configuration issue.. Can you create any std::threads at all?
Last edited on
You are doing o(n) when you could easily be doing o( n/2 ).
What you should do is check if it is divisble by 2. Then loop starting at 3 and increment by 2. If you wanted to save even more time processing you could set another counter and every 3rd time then increment by 4 instead of 2.
Topic archived. No new replies allowed.