/** * Example of returning a value from threads */ #include #include #include #include using namespace std; // global mutex mutex process_mutex; struct S { size_t x; }; void calculate(S s, int& result) { int out = s.x * 2; { // gard access to the sheared resource, i.e. cout lock_guard lock(process_mutex); cout << "threadid=" << this_thread::get_id() <<": x=" << s.x << " out=" << out << endl; } result = out; } int main() { size_t no_of_threads = 5; // this will store the values calculated by thread. vector results(no_of_threads, 0); // vector of threads vector threads; // create threads for(size_t i = 0; i < no_of_threads; ++i) { threads.emplace_back(&calculate, S{i}, ref(results.at(i))); } // wait for their completion and display results. for(size_t i = 0; i < no_of_threads; ++i) { threads.at(i).join(); } cout << endl << endl; // display results. for(size_t i = 0; i < no_of_threads; ++i) { cout << "x=" << i << " out=" << results.at(i) << endl; } return 0; }