我是C语言和Linux的新手,英语不是我的母语。提前对不起。
我正在研究在Linux上实现循环调度程序的学校项目,我在实现调度程序和thread_self方面遇到了一些问题。
调度程序首先检查就绪队列是否为空,如果是,则设置时间片和警报(时间片)。否则,从就绪列表中查找新线程,调度新线程的TCB,设置时间片,上下文切换到新线程并设置警报(timeslice)。但是我在某些时候仍然遇到错误,我找不到要修复的地方。
另一件事是关于thread_cancel。 int thread_cancel(thread_t tid)函数删除目标tcb,我需要使用tid找到tcb。我试过像
Thread* temp = getpid();
kill(pid, SIGKILL);
但我无法弄清楚如何从队列中删除tcb。 请给我一些更好的主意!
Thread.h
typedef struct _Thread{
ThreadStatus status;
pid_t pid;
Thread* pPrev;
Thread* pNext;
}Thread;
Thread* ReadyQHead;
Thread* ReadyQTail;
-Queue
typedef struct _queue{
Thread* head;
Thread* tail;
unsigned int num;
} queue;
queue* runList;
queue* readyList;
queue* waitList;
-Queue.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;
}
-Scheduler
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);
}