c - 实现线程调度器循环和线程取消

标签 c linux multithreading scheduler round-robin

我对 C 语言和 linux 很陌生,英语不是我的母语。提前为那些人道歉。

我正在做学校项目,该项目是在 Linux 上实现循环调度程序,但我在实现调度程序和 thread_self 时遇到了一些问题。

调度器首先检查就绪队列是否为空,如果是则设置时间片和警报(timeslice)。否则,从就绪列表中查找一个新线程,调度新线程的TCB,设置时间片,上下文切换到新线程并设置alarm(timeslice)。但我在某些时候不断出错,而且我找不到修复的地方。

另一件事是关于thread_cancel。 int thread_cancel(thread_t tid) 函数删除目标 tcb,我需要使用 tid 找到 tcb。我试过了

Thread* temp = getpid();
kill(pid, SIGKILL);

但我不知道如何从队列中删除 tcb。 请给我一些更好的主意!

线程.h

typedef struct _Thread{
    ThreadStatus status;
    pid_t pid;
    Thread* pPrev;
    Thread* pNext;
}Thread;
Thread* ReadyQHead;
Thread* ReadyQTail;

-队列

typedef struct _queue{
    Thread* head;
    Thread* tail;
    unsigned int num;
} queue;

queue* runList;
queue* readyList;
queue* waitList; 

-队列.c

void enqueue(queue * q, Thread* tcb)
{
    if(q->num == 0) {
        q->head = tcb;
        q->tail = tcb;
    } else {
        q->tail->pNext = tcb;
        q->tail = tcb;
    }
    q->num ++;
}

Thread * dequeue(queue * q)
{
    Thread * tmp;
    if(q->num == 0) return NULL;
    else if(q->num == 1) {
        tmp = q->head;
        q->head = NULL;
        q->tail = NULL;
    } else {
        tmp = q->head;
        q->head = q->head->pNext;
    }
    q->num --;
    return tmp;
}

-调度器

void alarmHandler(int signal)
{
    printf("Scheduler awake!!");
    /*Do schedule*/
}

int RunScheduler( void )
{
    //check if ready queue is empty
    if(is_empty(readyList) != 0)
    {
        printf("this is weird");
        signal(SIGALRM, alarmHandler);
    }
    else {
        /*Look up a new thread from ready list*/
        Thread* tmp = ReadyQHead;

        /*send sigcont*/
        kill(tmp->pid, SIGCONT);

        //dispatch TCB of new thread
        if(is_empty(runList) != 0 && runList->head->status == 0)
            enqueue(readyList, tmp);

        //pick thread at head of ready list as first thread to dispatch
        tmp->status = 0; // tmp == runningTcb
        printf("alive tcb : %d\n", tmp->pid);

        ReadyQHead = dequeue(readyList);
        //set timeslice
        signal(SIGALRM, alarmHandler);
        //context switch to new thread
        _ContextSwitch(tmp->pid, ReadyQHead->pid);

    }

    while(1){
        alarm(TIMESLICE);
    }

    return 0;
}


void _ContextSwitch(int curpid, int tpid)
{
    kill(curpid, SIGSTOP);
    kill(tpid, SIGCONT);
}

最佳答案

这里是一个round robin的简单例子

while(1)
{
    process1();
    process2();
    process3();
    process4();
    ....
    processN();
}

任何更复杂的事情,例如进程“休眠”时的上下文切换或等待 I/O 时的上下文切换或上下文切换,因为进程需要定时运行或由于中断事件而增加了巨大的复杂性.

那么您的目标/目标到底是什么?

关于c - 实现线程调度器循环和线程取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40864224/

相关文章:

for循环中fork后的进程计数

linux - 我如何知道 Bash 脚本中的脚本文件名?

java - 需要一个基于 Java 的可中断计时器线程

c - 从格式未知的文本文件中读取

C - 将结构内部的指针重新分配给结构外部的指针

kernel - 内存测试.c linux

c++ - 如何让它同步运行?

c - 使用分散聚集处理短读/写的技术?

linux - centos无法删除目录

Java 线程在隐藏到系统托盘时停止