Skip to content

Instantly share code, notes, and snippets.

@marcinwol
Created July 3, 2015 00:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcinwol/bc0c8b48f7a116efbdd1 to your computer and use it in GitHub Desktop.
Save marcinwol/bc0c8b48f7a116efbdd1 to your computer and use it in GitHub Desktop.
Example of returning values from threads
/**
* 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