Skip to content

Instantly share code, notes, and snippets.

@tornikegomareli
Created April 18, 2017 17:14
Show Gist options
  • Save tornikegomareli/45a3e41aaac8e09f1f2828f0e5dd9d31 to your computer and use it in GitHub Desktop.
Save tornikegomareli/45a3e41aaac8e09f1f2828f0e5dd9d31 to your computer and use it in GitHub Desktop.
Async function call in C++ with future library
// async example
#include <iostream>
#include <future>
using namespace std;
void Init(int Array[], int Size)
{
for (int i = 0; i < Size; i++)
{
Array[i] = i + 1;
}
}
bool Sorting(int Array[],const int length)
{
std::cout << "Calculating. Please, wait...\n";
for (int i = 0; i < length; i++)
{
for (int j = i+1; j < length; j++)
{
if (Array[i] > Array[j])
{
int tmp = Array[i];
Array[i] = Array[j];
Array[j] = tmp;
}
}
}
return true;
}
int main()
{
const int Size = 100000;
int Array[Size];
Init(Array, Size);
// call Sorting() function asynchronously:
std::future<bool> fut = std::async(Sorting,Array,Size);
std::cout << "Sorting the Array...." << endl;
for (int i = 0; i < 10000; i++)
{
cout << Array[i] << endl;
}
bool ret = fut.get();
if (ret)
std::cout << "It is done !\n";
else
std::cout << "It is not done.\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment