2011-11-06 60 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中的線性搜索引起的性能問題,因爲線程數量很大時可能會出現問題。在這種情況下,它可能對更復雜的結構有所幫助,併爲不同級別的優先級提供不同的線程列表。 再見!