Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You still need mutexes and conditions. Joining a thread makes one thread of execution wait for another thread to finish running. You still need mutexes to protect shared resources. It allows main() in this example to wait for all threads to finish before quitting itself.</p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;chrono&gt; #include &lt;mutex&gt; using namespace std; int global_counter = 0; std::mutex counter_mutex; void five_thread_fn(){ for(int i = 0; i&lt;5; i++){ counter_mutex.lock(); global_counter++; counter_mutex.unlock(); std::cout &lt;&lt; "Updated from five_thread" &lt;&lt; endl; std::this_thread::sleep_for(std::chrono::seconds(5)); } //When this thread finishes we wait for it to join } void ten_thread_fn(){ for(int i = 0; i&lt;10; i++){ counter_mutex.lock(); global_counter++; counter_mutex.unlock(); std::cout &lt;&lt; "Updated from ten_thread" &lt;&lt; endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } //When this thread finishes we wait for it to join } int main(int argc, char *argv[]) { std::cout &lt;&lt; "starting thread ten..." &lt;&lt; std::endl; std::thread ten_thread(ten_thread_fn); std::cout &lt;&lt; "Running ten thread" &lt;&lt; endl; std::thread five_thread(five_thread_fn); ten_thread.join(); std::cout &lt;&lt; "Ten Thread is done." &lt;&lt; std::endl; five_thread.join(); std::cout &lt;&lt; "Five Thread is done." &lt;&lt; std::endl; } </code></pre> <p>Note that the output might look like this:</p> <pre><code>starting thread ten... Running ten thread Updated frUopmd atteend_ tfhrroema df ive_thread Updated from ten_thread Updated from ten_thread Updated from ten_thread Updated from ten_thread Updated from five_thread Updated from ten_thread Updated from ten_thread Updated from ten_thread Updated from ten_thread Updated from ten_thread Updated from five_thread Ten Thread is done. Updated from five_thread Updated from five_thread Five Thread is done. </code></pre> <p>Since std::cout is a shared resource access and use of it should also be mutex protected too.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload