Skip to content

Instantly share code, notes, and snippets.

@odeblic
Last active July 27, 2017 11:29
Show Gist options
  • Save odeblic/02a4496502a548cb434230c33e0f9760 to your computer and use it in GitHub Desktop.
Save odeblic/02a4496502a548cb434230c33e0f9760 to your computer and use it in GitHub Desktop.
Asynchronous features (async, promises, futures)
#include <iostream>
#include <future>
#include <thread>
std::mutex mu;
template <typename T>
void print(std::string message, T data)
{
std::lock_guard<std::mutex> lg(mu);
std::cout << message << data << std::endl;
}
int computation(int arg)
{
print("computation begins for ", arg);
std::this_thread::sleep_for(std::chrono::seconds(1));
print("computation ends for ", arg);
return 2 * arg + 1;
}
int action(std::future<int> fu)
{
print("action got ", fu.get());
return 0;
}
int main()
{
std::future<int> fu1 = std::async(std::launch::deferred , computation, 1010);
std::future<int> fu2 = std::async(std::launch::deferred , computation, 1020);
std::future<int> fu3 = std::async(std::launch::deferred , computation, 1030);
print("********** ", " started");
std::async(std::launch::async, action, std::move(fu1)).get();
std::async(std::launch::async, action, std::move(fu2)).get();
std::async(std::launch::async, action, std::move(fu3)).get();
print("********** ", " completed");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment