我正在尝试模拟 FCFS 调度程序,我这样做的方式是,当线程进入其中时,如果它不在队列中,我将其推送到队列中,但如果是,则检查是否有线程位于队列的头部(第一个),并且作业的剩余时间> 0。我的问题是如何将线程置于等待状态,直到它成为队列的头部?我听说条件变量可能有帮助,但不确定它们是如何工作的。
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??
}
}
最佳答案
条件变量允许操作系统暂停线程的执行,直到另一个线程发送信号将其唤醒。对于您的 else 语句,您需要类似的内容
pthread_cond_wait(&cond_var, &mutex_var);
这将使线程进入休眠状态。但是,您还需要考虑何时唤醒线程。如果线程不在队列的头部,那么您可能应该使用 pthread_cond_broadcast 来唤醒所有等待的线程。您还需要一个循环,以便每个线程在每次唤醒时检查条件。因此,您最初的 if
语句可能应该类似于 while
循环。
关于c - 实现 FCFS 调度程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970785/