实现FCFS调度程序

时间:2013-02-20 01:30:26

标签: c multithreading pthreads semaphore

我正在尝试模拟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??
            }
        }

1 个答案:

答案 0 :(得分:0)

条件变量允许OS暂停执行线程,直到另一个线程发送信号将其唤醒。对于你的其他陈述,你需要像

这样的东西
pthread_cond_wait(&cond_var, &mutex_var);

那会让一个线程入睡。但是,您还需要考虑何时唤醒线程。可能如果一个线程不在队列的头部,那么你应该使用pthread_cond_broadcast来唤醒所有等待的线程。您还需要一个循环,以便每个线程在每次唤醒时检查条件。因此,您的初始if语句应该类似于while循环。

相关问题