#include // std::cout #include // std::atomic #include // std::thread #include // std::vector using namespace std; atomic atomic_counter (0); int unsync_counter = 0; void increase_atomic(int n) { for (int i=0; i &threads) { cout << "wait for all threads..." << endl; int joined = 0; for (auto & th : threads) { th.join(); joined++; } threads.clear(); cout << "join'ed " << joined << " threads" << endl; } int main (int argc, char *argv[]) { vector threads; cout << endl << "increase atomic counter with 10 threads..." << endl; auto t1 = chrono::high_resolution_clock::now(); for (int i=1; i<=10; ++i) threads.push_back(thread(increase_atomic, 10000000)); waitForThreads(threads); auto t2 = chrono::high_resolution_clock::now(); cout << "atomic counter: " << atomic_counter << endl; cout << chrono::duration_cast(t2 - t1).count() << " microseconds" << endl; cout << endl << "increase unsynchronized counter with 10 threads..." << endl; t1 = chrono::high_resolution_clock::now(); for (int i=1; i<=10; ++i) threads.push_back(thread(increase_unsync, 10000000)); waitForThreads(threads); t2 = chrono::high_resolution_clock::now(); cout << "unsync counter: " << unsync_counter << endl; cout << chrono::duration_cast(t2 - t1).count() << " microseconds" << endl; return 0; }