I'm very new in C language and linux and English is not my mother language. Sorry for those in advance.
I'm working on school project which is to implement a round robin scheduler on linux and I have some problems on implementing scheduler and thread_self.
Scheduler checks if ready queue is empty first, if yes set time slice and alarm(timeslice). Otherwise, look up a new thread from ready list, dispatch TCB of new thread, set timeslice, context switch to new thread and set alarm(timeslice). But I keep getting error at some point and I couldn't find where to fix.
Another thing is about thread_cancel. int thread_cancel(thread_t tid) function removes target tcb and I need to find the tcb using tid. I tried like
Thread* temp = getpid();
kill(pid, SIGKILL);
but I couldn't figure out how to remove tcb from queue. Please give me some better idea!
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);
}