Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::async doesn't parallelize tasks

Tags:

c++

gcc

c++11

Using C++11 std::async in this snippet:

int foo()
{
    ::sleep(2);
    return 123;
}

int main()
{
    future<int> r1(async(foo));
    int r2 = foo();
    cout << r1.get() + r2 << endl;
    return 0;
}

It produces the right result, but runs both foo's serially (whole app runs 4 seconds). Compiled as: g++ -std=gnu++11 -O2 foo.cc -lpthread (Ubuntu 12.10 64bit, gcc 4.7.2)

like image 437
Cartesius00 Avatar asked Dec 26 '22 14:12

Cartesius00


1 Answers

You might need to add a launch policy of std::launch::async:

std::async(std::launch::async, foo);
like image 195
Some programmer dude Avatar answered Jan 05 '23 23:01

Some programmer dude