title: C++ threads producer consumer
body: <p>I need to implement a piggy bank simulation where clients can either deposit or withdraw money from. The clients should be represented as threads, and the piggy bank is an integer variable. I need to create two functions called producer and consumer, which should be able to deposit or withdraw an amount defined by a parameter. Restrictions are that the consumer should only withdraw if there is enough money in the piggy bank. If not, it should wait for the piggy bank to fill up.</p>
  
  <p>The consumer and producer have to simultaneously access the piggy bank, and add or remove random amounts.</p>
  
  <p>I'm having troubles with this. I'm new to both c++ and threads. I have looked at different consumer producer solutions, but I can't find anything that helps.</p>
  
  <p>This is my code so far. I reckon the structure is correct, but</p>
  
  <pre><code> #include &lt;iostream&gt;
   #include &lt;thread&gt;
   #include &lt;mutex&gt;
   #include &lt;condition_variable&gt;
  
   using namespace std;
  
   int piggybank;
   mutex mlock;
   condition_variable sem;
   bool available = false;
  
   void consumer(int amount){
       unique_lock&lt;mutex&gt; lck(mlock);
       sem.wait(lck);
       piggybank -= amount;
   }
  
   void producer(int amount){
       unique_lock&lt;mutex&gt; lck(mlock);
       piggybank += amount;
       //available = piggybank &gt; 50;
       sem.notify_all();
   }
  
   int main() {
       piggybank = 0;
  
       thread cons(consumer, rand()%50+1);
       thread prod(producer, rand()%50+1);
  
       prod.join();
       cons.join();
  
       return 0;
   } 
  </code></pre>
  
  <p>I need some sort of condition, but I don't know how to use the conditional variable. </p>