45
edits
Changes
no edit summary
Finished at 6 milliseconds
===Asynchronous Multi-Threading===
C++ 11 allows the creation of asynchronous threads using the std:async template function part of the <future> header. The function returns a std::future type that will store the expected return value of std::async’s parameter function. A future is an object that can retrieve a value from some provider object (also known as a promise) or function. Simply put in the case of multithreading, a future object will wait until its associated thread has completed and then store its return value.
To retrieve or construct a future object, these functions may be used.
• Async
• promise::get_future
• packaged_task::get_future
However, a future object can only be used if it is in a valid state. Default future objects constructed from the std::async template function are not valid and must be assigned a valid state during execution.
A std::future references a shared state that cannot be shared to other asynchronous return objects. If multiple threads need to wait for the same shared state, std::shared_future class template should be used.
Basic example of asynchronous multi-threading using std::async to create the thread and std::future to store the return result of their associated threads.
#include <vector>
#include <iostream>
#include <chrono>
#include <future>
int twice(int m){
return 2 * m;
}
int main(int argc, char *argv[])
{
std::vector<std::future<int>> futures;
for (int i = 0; i < 10; ++i) {
futures.push_back(std::async(twice, i));
}
for (int i = 0; i < futures.size(); i++){
std::cout << futures.at(i).get() << std::endl;
}
return 0;
}
===Programming Models===