Threads in C++: Example 2
•
C++ provides an even higher level of abstraction that avoids
the concept of threads altogether and uses tasks instead.
Simple example:
#
#
include <iostream>
The async construct uses an object pair called a
include <future>
promise and a future: the future is linked to the
promise and can at any time try to retrieve the
value (get()). If the promise hasn't been fulfilled
yet, it will simply wait until the value is ready.
using namespace std;
int square(int x){
return x * x;
}
int main(){
future<int> mytask = async(launch::async, square, 10);
int value = mytask.get();
cout << "The thread returned " << value << endl;
return 0;
}