std::async uses same thread and my code does not achieve parallelism. std::async uses same thread and my code does not achieve parallelism. multithreading multithreading

std::async uses same thread and my code does not achieve parallelism.


            async(launch::async, foo, i, move(prmsVec[i]));

This line returns a future but because you do not assign it to anything the future's destructor runs at the end of the statement, which blocks and waits for the result by calling std::future::wait()

Why are you manually calling std::async with a promise, when it returns a future anyway? The point of async is that you don't need to manually use a promise, that's done internally for you.

Rewrite your foo() to return double then call it with async

#include <mutex>#include <future>#include <thread>#include <vector>#include <cmath>#include <iostream>using namespace std;mutex iomutex;double foo(int i){    this_thread::sleep_for(chrono::seconds(2));    lock_guard<mutex> lg(iomutex);    cout << "\nthread index=> " << i << ", id=> "<< this_thread::get_id();    return sqrt(i);}int main(){    cout << "\nmain thread id=>" << this_thread::get_id();    vector<future<double>> futureVec;    for (int i = 0; i < 10; ++i)        futureVec.push_back(async(launch::async, foo, i));    for (auto& fut : futureVec)    {        auto x = fut.get();        lock_guard<mutex> lg(iomutex);        cout << endl << x;    }    cout << "\ndone\n";}