title: Simulating round robin with pthreads
body: <p>The task is to have 5 threads present at the same time, and the user assigns each a burst time. Then a round robin algorithm with a quantum of 2 is used to schedule the threads. For example, if I run the program with</p>
  
  <pre><code>$ ./m 1 2 3 4 5
  </code></pre>
  
  <p>The output should be</p>
  
  <pre><code>A 1
  B 2
  C 2
  D 2
  E 2
  C 1
  D 2
  E 2
  E 1
  </code></pre>
  
  <p>But for now my output shows only</p>
  
  <pre><code>A 1
  B 2
  C 2
  </code></pre>
  
  <p>Since the program errs where one thread does not end for the time being, I think the problem is that this thread cannot unlock to let the next thread grab the lock. My sleep() does not work, either. But I have no idea how to modify my code in order to fix them. My code is as follows:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  double times[5];
  char process[] = {'A', 'B', 'C', 'D', 'E'};
  int turn = 0;
  
  void StartNext(int tid)     //choose the next thread to run
  {
      int i;
      for(i = (tid + 1) % 5; times[i] == 0; i = (i + 1) % 5)
          if(i == tid)    //if every thread has finished
              return;
      turn = i;
  }
  
  void *Run(void *tid)    //the thread function
  {
      int i = (int)tid;
      while(times[i] != 0)
      {
          while(turn != i);   //busy waiting till it is its turn
          if(times[i] &gt; 2)
          {
              printf("%c 2\n", process[i]);
              sleep(2);   //sleep is to simulate the actual running time
              times[i] -= 2;
          }
          else if(times[i] &gt; 0 &amp;&amp; times[i] &lt;= 2)      //this thread will have finished after this turn
          {
              printf("%c %lf\n", process[i], times[i]);
              sleep(times[i]);
              times[i] = 0;
          }
          StartNext(i);   //choose the next thread to run
      }
      pthread_exit(0);
  }
  
  int main(int argc, char **argv)
  {
      pthread_t threads[5];
      int i, status;
  
      if(argc == 6)
      {
          for(i = 0; i &lt; 5; i++)
              times[i] = atof(argv[i + 1]);   //input the burst time of each thread
          for(i = 0; i &lt; 5; i++)
          {
              status = pthread_create(&amp;threads[i], NULL, Run, (void *)i);    //Create threads
              if(status != 0)
              {
                  printf("While creating thread %d, pthread_create returned error code %d\n", i, status);
                  exit(-1);
              }
              pthread_join(threads[i], 0);    //Join threads
          }
      }
      return 0;
  }
  </code></pre>
  
  <p>The program is directly runnable. Could anyone help me figure it out? Thanks!</p>