Skip to content

Instantly share code, notes, and snippets.

@Ignition
Created October 29, 2012 14:58
Show Gist options
  • Save Ignition/3974017 to your computer and use it in GitHub Desktop.
Save Ignition/3974017 to your computer and use it in GitHub Desktop.
Example of using future C++11
#include <iostream>
#include <future>
#include <thread>
int main()
{
// future from a packaged_task
std::packaged_task<int()> task([](){ return 7; }); // wrap the function
std::future<int> f1 = task.get_future(); // get a future
std::thread(std::move(task)).detach(); // launch on a thread
// future from an async()
std::future<int> f2 = std::async(std::launch::async, [](){ return 8; });
// future from a promise
std::promise<int> p;
std::future<int> f3 = p.get_future();
std::thread( [](std::promise<int>& p){ p.set_value(9); }, std::ref(p) ).detach();
std::cout << "Waiting...";
f1.wait();
f2.wait();
f3.wait();
std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
}
//g++ thisgist.cpp -std=c++11 -pthread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment