2013-02-20 61 views
0

我想模拟一个FCFS调度程序,我这样做的方式是当一个线程进来时,如果它不在队列中,我推它在队列中,但如果它是检查线程是否在队列的头部(先进入),并且作业的剩余时间大于0.我的问题是如何将线程置于等待状态,直到它成为队列头部?我听说条件变量可能有帮助,但不知道它们是如何工作的。实现一个FCFS调度程序

if (!(is_in_queue(ready_queue, tid))) { //thread is not in the queue 
      pthread_mutex_lock(&schedule_lock); 
      ready_queue = enqueue(ready_queue, currentTime, tid, remainingTime, tprio); 
      pthread_mutex_unlock(&schedule_lock); 
     } 
     else{ //thread is in queue 
      if (tid == head_of_queue(ready_queue) && remainingTime >0) { //need to schedule this thread for full time 
       return currentTime +1; //schedule on the next unit of "time" 
      } 
      else if (tid == head_of_queue(ready_queue) && remainingTime == 0){ //need to go to next task 
       pthread_mutex_lock(&schedule_lock); 
       ready_queue = dequeue(ready_queue); 
       pthread_mutex_unlock(&schedule_lock); 
      } 
      else{ //not at the head of the queue 
       //How do i wait until it is at the head?? 
      } 
     } 

回答

0

条件变量允许操作系统挂起线程的执行,直到另一个线程发送一个信号唤醒它为止。为了您的其他声明,您需要类似于

pthread_cond_wait(&cond_var, &mutex_var); 

这将使线程进入睡眠状态。但是,您还需要考虑何时唤醒线程。可能如果一个线程不在队列的头部,那么你应该使用pthread_cond_broadcast来唤醒所有等待的线程。您还需要一个循环,以便每个线程在每次唤醒时检查条件。所以你的初始if声明可能应该像while循环。