I'm having trouble understanding what it is necessarily used for?
Consider this piece of C++11 code:
#include <future>
#include <atomic>
#include <vector>
#include <iostream>
int main() {
int value = 0;
std::vector< std::future< int > > results;
results.emplace_back( std::async( [&value]() -> int { return value += 2; } ) );
results.emplace_back( std::async( [&value]() -> int { return value += 3; } ) );
for(auto& x : results)
std::cout << x.get() << " ";
std::cout << value << std::endl;
};
If you are not familiar with C++11 concurrency features (like std::future
and std::async
) I recommend you look it up. In essence, this code creates two threads (via async
) that will execute a function that increments a shared value (value
) by either 2 or 3, respectively. Then, the results are printed out, and then, the final value of the shared value is printed too.
The million dollar question here is: What will this code print out?
The stupid answer:
It should print out 2 5 5
. If you have no idea what threads are or how they work, you might think that this code is obvious: start with (value == 0)
, then increment it by 2 and store the result in the vector, then increment it by 3 and store the result in the vector, and finally, the value ends up with a value of 5. However, you can't rely on the "first" thread executing "first", because they can either execute simultaneously or …