title: (C++ Threads): Creating worker threads that will be listening to jobs and executing them concurrently when wanted
body: <p>Suppose we have two workers. Each worker has an id of <code>0</code> and <code>1</code>. Also suppose that we have jobs arriving all the time, each job has also an identifier <code>0</code> or <code>1</code> which specifies which worker will have to do this job.</p>
  
  <p>I would like to create 2 threads that are initially locked, and then when two jobs arrive, unlock them, each of them does their job and then lock them again until other jobs arrive.</p>
  
  <p>I have the following code:</p>
  
  <pre><code>  #include &lt;iostream&gt;
    #include &lt;thread&gt;
    #include &lt;mutex&gt;
  
    using namespace std;
  
    struct job{
  
        thread jobThread;
        mutex jobMutex;
  
    };
  
    job jobs[2];
  
  
    void executeJob(int worker){
  
        while(true){
  
            jobs[worker].jobMutex.lock();
  
            //do some job
  
        }
  
     }
  
    void initialize(){
  
        int i;
        for(i=0;i&lt;2;i++){
                  jobs[i].jobThread = thread(executeJob, i);
        }
  
     }
  
    int main(void){
  
        //initialization
        initialize();
  
        int buffer[2];
        int bufferSize = 0;
  
        while(true){
            //jobs arrive here constantly, 
              //once the buffer becomes full, 
              //we unlock the threads(workers) and they start working
            bufferSize = 2;
            if(bufferSize == 2){
                for(int i = 0; i&lt;2; i++){
                    jobs[i].jobMutex.unlock();
                }
            }
             break;
       }
  
    }
  </code></pre>
  
  <p>I started using <code>std::thread</code> a few days ago and I'm not sure why but Visual Studio gives me an error saying <code>abort() has been called</code>. I believe there's something missing however due to my ignorance I can't figure out what.</p>
  
  <p>I would expect this piece of code to actually</p>
  
  <ol>
  <li><p>Initialize the two threads and then lock them</p></li>
  <li><p>Inside the main function unlock the two threads, the two threads will do their job(in this case nothing) and then they will become locked again.</p></li>
  </ol>
  
  <p>But it gives me an error instead. What am I doing wrong?</p>
  
  <p>Thank you in advance!</p>