C 为用户空间线程库编写调度程序
我正在开发一个用户空间前置线程库(fibre),它使用上下文切换作为基本方法。为此,我编写了一个调度程序。然而,它的表现并不像预期的那样。我能对此有什么建议吗。 所用螺纹的结构为:C 为用户空间线程库编写调度程序,c,multithreading,operating-system,scheduling,C,Multithreading,Operating System,Scheduling,我正在开发一个用户空间前置线程库(fibre),它使用上下文切换作为基本方法。为此,我编写了一个调度程序。然而,它的表现并不像预期的那样。我能对此有什么建议吗。 所用螺纹的结构为: typedef struct thread_t { int thr_id; int thr_usrpri; int thr_cpupri; int thr_totalcpu; ucontext_t thr_context; void * thr_stack; i
typedef struct thread_t {
int thr_id;
int thr_usrpri;
int thr_cpupri;
int thr_totalcpu;
ucontext_t thr_context;
void * thr_stack;
int thr_stacksize;
struct thread_t *thr_next;
struct thread_t *thr_prev;
} thread_t;
调度功能如下所示:
void schedule(void)
{
thread_t *t1, *t2;
thread_t * newthr = NULL;
int newpri = 127;
struct itimerval tm;
ucontext_t dummy;
sigset_t sigt;
t1 = ready_q;
// Select the thread with higest priority
while (t1 != NULL)
{
if (newpri > t1->thr_usrpri + t1->thr_cpupri)
{
newpri = t1->thr_usrpri + t1->thr_cpupri;
newthr = t1;
}
t1 = t1->thr_next;
}
if (newthr == NULL)
{
if (current_thread == NULL)
{
// No more threads? (stop itimer)
tm.it_interval.tv_usec = 0;
tm.it_interval.tv_sec = 0;
tm.it_value.tv_usec = 0; // ZERO Disable
tm.it_value.tv_sec = 0;
setitimer(ITIMER_PROF, &tm, NULL);
}
return;
}
else
{
// TO DO :: Reenabling of signals must be done.
// Switch to new thread
if (current_thread != NULL)
{
t2 = current_thread;
current_thread = newthr;
timeq = 0;
sigemptyset(&sigt);
sigaddset(&sigt, SIGPROF);
sigprocmask(SIG_UNBLOCK, &sigt, NULL);
swapcontext(&(t2->thr_context), &(current_thread->thr_context));
}
else
{
// No current thread? might be terminated
current_thread = newthr;
timeq = 0;
sigemptyset(&sigt);
sigaddset(&sigt, SIGPROF);
sigprocmask(SIG_UNBLOCK, &sigt, NULL);
swapcontext(&(dummy), &(current_thread->thr_context));
}
}
}
“ready_q”(ready线程列表的头?)似乎永远不会改变,因此搜索优先级最高的线程总是会找到第一个合适的元素。如果两个线程具有相同的优先级,则只有第一个线程有机会获得CPU。您可以使用许多算法,一些算法基于优先级的动态变化,另一些算法在就绪队列中使用某种轮换。在您的示例中,您可以将所选线程从就绪队列中的位置移除,并放在最后一个位置(它是一个双链接列表,因此该操作非常简单且成本低廉)。
此外,我建议您考虑在RealyQuq中的线性搜索引起的性能问题,因为当线程的数量很大时可能会出现问题。在这种情况下,一个更复杂的结构可能会有所帮助,它具有不同优先级的不同线程列表。
再见 它在做什么是“不期望的”?好吧,一旦主线程将控制传递给另一个线程,它就不会被调度回很长一段时间。也许是优先级反转。不过不确定。