Created
July 3, 2015 00:38
-
-
Save marcinwol/bc0c8b48f7a116efbdd1 to your computer and use it in GitHub Desktop.
Example of returning values from threads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example of returning a value from threads | |
*/ | |
#include <iostream> | |
#include <vector> | |
#include <mutex> | |
#include <thread> | |
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<mutex> 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<int> results(no_of_threads, 0); | |
// vector of threads | |
vector<thread> 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment