Re: how do threads work?
From: Pascal Bourguignon (spam_at_mouse-potato.com)
Date: Sat, 19 Nov 2005 16:05:10 +0100
Andersen <email@example.com> writes:
> Pascal Bourguignon wrote:
>> When you want to context switch, you save all the registers on the
>> current stack, and store the stack pointer into the current thread
>> structure, then you change the current thread, you fetch the new stack
>> pointer from the new current thread structure, and you restore the
>> registers. Context switch done.
>> Now the problem is to do it premptively. Since on unix normally the
>> only asynchronous events a process can receive are signals, we should
>> us them. But if we switch the context in the middle of a signal
>> handling function, I'm not sure all systems will appreciate: it's
>> better to return from the signal handler. So what you can do is to
>> use SIGALRM, and in the signal handler, you pop the signal stack
>> frame and save it temporarily, do the context switching, push the
>> saved signal stack frame, and return from the signal handler. You
>> need to know how to determine the size of signal stack frame.
> Do not get it. You mean the actual preemption is done by using
> How is that implemented on a machine such as IA32. I mean how
> can a user-level thread library preempt a thread?
With an timer signal: SIGALRM, SIGVTARLM, etc. See setitimer(2)
You can also use sigaltstack, that was what I was thinking about, to
have the signal delivered on a distinct stack so you don't have to
bother with the signal stack frame.
When you do a thread context switch, mind updating the stack limit:
setrlimit(RLIMIT_STACK, &rlim) to match that of the thread stack.
> Stack frame = registers and return address saved on the stack before a
> function call?
Yes. Namely: struct sigframe.
The best source of information will be: /usr/src/linux
You can fetch the stack pointer of the interupted thread in the
sigcontext field of the sigframe. (Or refer to rt_sigframe if you use
a real-time signal). Exchanging the sigcontext records of the threads
to switch, in the sigframe, should be all you need to do to do the
thread context switch.
-- __Pascal Bourguignon__ http://www.informatimago.com/ Until real software engineering is developed, the next best practice is to develop with a dynamic system that has extreme late binding in all aspects. The first system to really do this in an important way is Lisp. -- Alan Kay