title: How to use sched_yield() properly?
body: <p>For an assignment, I need to use <code>sched_yield()</code> to synchronize threads. I understand a mutex lock/conditional variables would be much more effective, but I am not allowed to use those.</p>
  <p>The only functions we are allowed to use are <code>sched_yield()</code>, <code>pthread_create()</code>, and <code>pthread_join()</code>. We cannot use mutexes, locks, semaphores, or any type of shared variable.</p>
  <p>I know <code>sched_yield()</code> is supposed to relinquish access to the thread so another thread can run. So it should move the thread it executes on to the back of the running queue.</p>
  <p>The code below is supposed to print 'abc' in order and then the newline after all three threads have executed. I looped <code>sched_yield()</code> in functions <code>b()</code> and <code>c()</code> because it wasn't working as I expected, but I'm pretty sure all that is doing is delaying the printing because a function is running so many times, not because <code>sched_yield()</code> is working.</p>
  <p>The server it needs to run on has 16 CPUs. I saw somewhere that <code>sched_yield()</code> may immediately assign the thread to a new CPU.</p>
  <p>Essentially I'm unsure of how, using only <code>sched_yield()</code>, to synchronize these threads given everything I could find and troubleshoot with online.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sched.h&gt;
  
  void* a(void*);
  void* b(void*);
  void* c(void*);
  
  int main( void ){
      pthread_t a_id, b_id, c_id;
      pthread_create(&amp;a_id, NULL, a, NULL);
      pthread_create(&amp;b_id, NULL, b, NULL);
      pthread_create(&amp;c_id, NULL, c, NULL);
  
      pthread_join(a_id, NULL);
      pthread_join(b_id, NULL);
      pthread_join(c_id, NULL);
  
      printf(&quot;\n&quot;);
  
      return 0;
  }
  
  void* a(void* ret){
      printf(&quot;a&quot;);
      return ret;
  }
  
  void* b(void* ret){
      for(int i = 0; i &lt; 10; i++){
          sched_yield();
      }
      printf(&quot;b&quot;);
      return ret;
  }
  
  void* c(void* ret){
      for(int i = 0; i &lt; 100; i++){
          sched_yield();
      }
      printf(&quot;c&quot;);
      return ret;
  }
  </code></pre>