c - 实现 FCFS 调度程序

标签 c multithreading pthreads semaphore

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

相关文章:

c - 为什么会出现访问冲突运行时错误?

C++如何调用带参数的线程

c - TFTP 中的超时和重新传输问题

c++ - 线程作为类,如何保证子类的数据被销毁?

c - 格式指定类型 'int' 但打印尺寸时参数出现类型 'unsigned long' 错误

c - 为什么我应该使用双指针变量来接收另一个指针的地址(&ptr1)

c - 为什么我的输出没有随着每次循环迭代而改变?

java - 如何同步不同的java程序访问公共(public)资源

C++ - 在后台 POSIX 线程上以固定增量时间循环

c++ - 使用 pThreads 在线程之间共享 3D 数组