C++ std::future and std::async


Example

In the following naive parallel merge sort example, std::async is used to launch multiple parallel merge_sort tasks. std::future is used to wait for the results and synchronize them:

#include <iostream>
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);
    }
}

Note: In the example std::async is launched with policy std::launch_deferred. This is to avoid a new thread being created in every call. In the case of our example, the calls to std::async are made out of order, the they synchronize at the calls for std::future::get().

std::launch_async forces a new thread to be created in every call.

The default policy is std::launch::deferred| std::launch::async, meaning the implementation determines the policy for creating new threads.