Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Fraser's answer is great, but when I looked at this I felt a working example would be nice.</p> <p>I made some changes:</p> <ul> <li><p>Personally, I like to use RAII to lock/unlock so that you don't forget to do so (even if it means extra scopes). In the past, I've also had race conditions that I couldn't figure out, and switching to the RAII approach has often made those disappear as well... It's just easier, so do it ;)</p></li> <li><p>I like to see when the cars leave, so I add I/O for that too.</p></li> </ul> <p>Here's the working code example for the stated problem. FYI, I use clang 3.1 with libc++:</p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; #include &lt;chrono&gt; using namespace std; int cars=0; int max_cars=5; mutex cars_mux; condition_variable cars_cond; bool pred() { return cars &lt; max_cars; } void task() { { unique_lock&lt;mutex&gt; carlock(cars_mux); cars_cond.wait(carlock,pred); cars++; cout &lt;&lt; "Thread " &lt;&lt; this_thread::get_id() &lt;&lt; " has parked. There are " &lt;&lt; cars &lt;&lt; " parked cars." &lt;&lt; endl; } this_thread::sleep_for(chrono::seconds(1)); { unique_lock&lt;mutex&gt; carlock(cars_mux); cars--; cout &lt;&lt; "Thread " &lt;&lt; this_thread::get_id() &lt;&lt; " has left. There are " &lt;&lt; cars &lt;&lt; " parked cars." &lt;&lt; endl; cars_cond.notify_one(); } } int main(int argc, char** argv) { const int NumThreads = 10; thread t[NumThreads]; for(int i=0; i&lt;NumThreads; i++) t[i]=thread(task); for(int i=0; i&lt;NumThreads; i++) t[i].join(); return 0; } </code></pre> <p>Edit: Simplified code as per Rami Al Zuhouri's suggestion.</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. 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.
 

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