title: pthreads - force thread to run
body: <p>I have a function that is invoked from the main thread:</p>
  
  <pre><code>void create_thread() {    
      pthread_t bg_thread;
      pthread_create(&amp;bg_thread, NULL, run_in_background, NULL);
  
      //wait here
      pthread_mutex_lock(&amp;MAIN_MUTEX);
      pthread_cond_wait(&amp;wakeUpMainThread, &amp;MAIN_MUTEX);
      pthread_mutex_unlock(&amp;MAIN_MUTEX);
  
      pthread_cond_signal(wakeUpBgThread);
  }
  </code></pre>
  
  <p>Here is the short version of the function that runs in background thread:</p>
  
  <pre><code>void* run_in_background(void* v) {                   
      pthread_mutex_t mutex;
      pthread_cond_t  cond;
      pthread_mutex_init(&amp;mutex, NULL);
      pthread_cond_init(&amp;cond, NULL);
  
      //NOTE: wakeUpBgThread == cond
      save_condition_and_mutex(&amp;cond, &amp;mutex);
  
      pthread_mutex_lock(&amp;mutex);
      {
          pthread_cond_signal(&amp;wakeUpMainThread);
  
          while( run_condition ) {
              pthread_cond_wait(&amp;cond, &amp;mutex);
  
              do_smth();
          }
      }
      pthread_mutex_unlock(&amp;mutex);
  
      pthread_mutex_destroy(&amp;mutex);
      pthread_cond_destroy(&amp;cond);
  
      pthread_exit(NULL);
  }
  </code></pre>
  
  <p>So the goal is: </p>
  
  <pre><code>1. Create a thread in the main one.
  2. Make the main thread sleep until the signal from that thread.
  3. Make the background thread sleep until the signal from the main thread.
  4. Invoke the background thread from the main one.
  </code></pre>
  
  <p>The problem is: sometimes after the</p>
  
  <pre><code> pthread_cond_signal(&amp;wakeUpMainThread);
  </code></pre>
  
  <p>scheduler switches to the main thread immediately and fires the wake up signal for the background thread. After this scheduler switches back to the background thread and it starts waiting for the signal that has already been fired, so it sleeps forever.</p>
  
  <p>Question: is there any way to force background thread to execute the code until the </p>
  
  <pre><code>pthread_cond_wait(&amp;cond, &amp;mutex);
  </code></pre>