std future and std async
suggest changeIn the following merge sort example, std::async launches merge_sort tasks and std::future waits for them. Both tasks use std::launch::deferred, so they run one after another on the thread that calls get(), not in parallel:
#include <future>
#include <iostream>
#include <vector>
using namespace std;
void merge(int low,int mid,int high, vector<int>&num)
{
vector<int> copy(num.size());
int h,i,j,k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(num[h]<=num[j])
{
copy[i]=num[h];
h++;
}
else
{
copy[i]=num[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
copy[i]=num[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
copy[i]=num[k];
i++;
}
}
for(k=low;k<=high;k++)
swap(num[k],copy[k]);
}
void merge_sort(int low,int high,vector<int>& num)
{
int mid;
if(low<high)
{
mid = low + (high-low)/2;
auto future1 = std::async(std::launch::deferred,[&]()
{
merge_sort(low,mid,num);
});
auto future2 = std::async(std::launch::deferred, [&]()
{
merge_sort(mid+1,high,num) ;
});
future1.get();
future2.get();
merge(low,mid,high,num);
}
}
In this example, std::async uses the std::launch::deferred policy, so each
callable runs only when its future is waited on or queried with get(). No new
worker thread is required. Although the asynchronous operations are created out
of order, the calls to std::future::get() determine their execution order.
std::launch::async forces a new thread to be created in every call. Using that policy for these lambdas would not be a data race, because the two tasks read and write disjoint ranges of num, but every recursive call would create a new thread.
The default policy is std::launch::deferred| std::launch::async, meaning the implementation determines the policy for creating new threads.