2011-11-06 38 views
0

我正在开发使用上下文切换作为基本方法的用户空间预先线程库(光纤)。为此我写了一个调度程序。但是,它没有按预期执行。我能为此提出任何建议吗? 的的thread_t所使用的结构是:为用户空间线程库编写调度程序

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)); 
     } 
    } 
} 
+0

它是干什么的“没有预料到”? –

+0

那么,一旦主线程将控制传递给其他线程,它就不会长时间回调。也许优先倒置。虽然不确定。 – uyetch

回答

1

看来,“ready_q”(?就绪线程列表的头)永远不会改变,所以对最高优先级线程的搜索总是找到第一个合适的元素。如果两个线程具有相同的优先级,则只有第一个线程有机会获得CPU。有许多算法可以使用,其中一些算法基于优先级的动态更改,其他算法则在就绪队列中使用某种旋转。在你的例子中,你可以将选中的线程从它在就绪队列中的位置删除,并放在最后一个地方(这是一个双链表,因此操作很简单,而且非常便宜)。 另外,我建议你考虑ready_q中的线性搜索引起的性能问题,因为线程数量很大时可能会出现问题。在这种情况下,它可能对更复杂的结构有所帮助,并为不同级别的优先级提供不同的线程列表。 再见!