【问题标题】:Writing a scheduler for a Userspace thread library为用户空间线程库编写调度程序
【发布时间】:2011-11-06 05:05:47
【问题描述】:

我正在开发一个使用上下文切换作为基本方法的用户空间抢占式线程库(光纤)。为此,我编写了一个调度程序。但是,它的表现不如预期。我可以对此有什么建议吗? 使用的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));
        }
    }
}

【问题讨论】:

  • 它在做什么是“没有预料到的”?
  • 嗯,一旦主线程将控制权交给其他线程,很长一段时间都不会被调度回来。也许优先级反转。不过不确定。

标签: c multithreading operating-system scheduling


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多