#include <iostream> #include <vector> #include <thread> #include <atomic> using namespace std; atomic<int> accum(0); void square(int x) { accum += x * x; } int main() { vector<thread> ths; for (int i = 1; i <= 20; i++) { ths.push_back(thread(&square, i)); } for (auto& th : ths) { th.join(); } cout << "accum = " << accum << endl; return 0; }
Die Variable temp muss in diesem Fall nicht einführt werden, da die Operation x*x vorher ausgewertet wird, bevor das Ergebnis zu accum weitergegeben wird, d.h. es ist außerhalb des atomic Ereignisses.