Skip to content

Instantly share code, notes, and snippets.

@juehan
Created January 14, 2013 10:17
Show Gist options
  • Save juehan/4529100 to your computer and use it in GitHub Desktop.
Save juehan/4529100 to your computer and use it in GitHub Desktop.
C++11 async() and future<> allow us task based parallel programming.
#include <future>
#include <iostream>
#include <vector>
int main()
{
std::cout << "Task parallerism using C++11 async() and future<>" << std::endl;
std::cout << "Main thread id: " << std::this_thread::get_id()
<< std::endl;
std::vector<std::future<void>> futures;
//create 20 task and store them in container
for (int i = 0; i < 20; ++i)
{
auto fut = std::async([]
{
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << std::this_thread::get_id() << " ";
});
futures.push_back(std::move(fut));
}
//run them and wait to be completed
std::for_each(futures.begin(), futures.end(), [](std::future<void> & fut)
{
fut.wait();
});
std::cout << "\n\nDone ..." << std::endl;
}
/*
output
Task parallerism using C++11 async() and future<>
Main thread id: 680
7864 7524 5352 6396 34884212 2820 7956 3928 6836 7284 7576 6248 2752 7316 464 5847424 7692 1640
Done ...
계속하려면 아무 키나 누르십시오 . . .
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment