views:

22

answers:

1

I'm trying to implement user threads on a 2.4 Linux kernel (homework) and the trick for context switch seems to be using an alarm that goes off every x milliseconds and sends us to an alarm handler from which we can longjmp to the next thread. What I'm having difficulties with is figuring out how to save the environment to return to later.

Basically I have an array of jmp_buffs, and every time a "context switch" using the alarm happens I want to save the previous context to the appropriate entry of the array and longjmp to the next one. However, just the fact that I need to do this from the event handler means that just using setjmp in the event handler won't give me exactly the kind of environment I want (as far as stack and program counter are involved) because the stack has the event handler call in it and the pc is in the event handler.

I suppose I can look at the stack and alter it to fit my needs, but that feels a bit cumbersome. Another idea I had is to somehow pass the environment before the jump to event handler as a parameter to the event handler, but I can't figure out if this is possible.

So I guess my question is- how do I do this right?

+1  A: 

You should be able to just do something like:

if (setjmp(&from_thread))
    return;
else
    longjmp(&dest_thread, 1);

in the event handler. Sure, it means it'll arrive back in the thread in the event handler - but that's OK because then you'll return straight out of it, so it'll go back to where the thread was when the event handler triggered.

(Of course this presumes that you've set up separate stacks for the threads already).

caf