0

I've got a very simple code snippet from cpprefernce.com, as follows:

#include<future>
#include<iostream>
using namespace std;
int main(){
    packaged_task<int(int)> t([](int i){return i+1;});
    auto f = t.get_future();
    cout<<"begin to call t\n";
    t(3);
    cout<<f.get()<<endl;
    return 0;
}

Once I run it with g++ on ubuntu18.04, it prints:

begin to call t
terminate called after throwing an instance of 'std::system_error'
what():  Unknown error -1
Aborted

So where does the program get wrong, how to fix it?

Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • Sorry, I don't quite get this point? – Troskyvs Jan 25 '20 at 02:57
  • Can't reproduce error here. Introduce a delay before calling f.get() or check f for readiness since future may not be ready then. – seccpur Jan 25 '20 at 03:27
  • The problem disappears when compiling with `-lpthread` flag. Tested on [Coliru](http://coliru.stacked-crooked.com/a/cc8083afbf635dc7). Try to build without `-lpthread` and see what happens. – rafix07 Jan 25 '20 at 08:49
  • Related https://stackoverflow.com/questions/41790363/c-core-dump-with-packaged-task/41790617 – rafix07 Jan 25 '20 at 08:51
  • Thanks for this link, problem is solved by using "-pthread" not "-lpthread" as linker flag. – Troskyvs Jan 25 '20 at 13:57

0 Answers0