Skip to content

Instantly share code, notes, and snippets.

@marcinwol
Created July 3, 2015 00:38
Show Gist options
  • Save marcinwol/bc0c8b48f7a116efbdd1 to your computer and use it in GitHub Desktop.
Save marcinwol/bc0c8b48f7a116efbdd1 to your computer and use it in GitHub Desktop.

Revisions

  1. marcinwol created this gist Jul 3, 2015.
    64 changes: 64 additions & 0 deletions return_value.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    /**
    * 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;
    }