开发者

where have example of context switching

assume function pointer pointed to A is passed to pthread_create and after the thread run, i change the address of function pointer to static function B from A

I do not understand how one thread switch bwetween two functions A and B with push and pop as i would like to save the context of function开发者_开发知识库 A when interrupt the thread of it

any example to show this context switching


It's hard to tell what you're asking here... but I'll give it a shot.

To address your first paragraph, I think what you're asking is what will happen when you pass a function pointer (which points to function A()) to pthread_create(), then modify the function pointer to point to a different function (function B()). The answer is that modifying the function pointer has no effect on the running thread; since you passed a copy of the function pointer to pthread_create(), the running thread will not detect that you modify your function pointer later on.

I believe you're really after something else, though: How is a thread context switch implemented? Let's assume for the moment that you're doing cooperative multitasking, i.e. a running thread explicitly needs to yield the CPU by calling a yield() function. Here's pseudocode for what a simple yield function might look like; we'll call the currently running thread "thread A" and the thread to which we're switching "thread B":

void yield()
{
    Save all registers to the stack
    Save current stack pointer in some data structure dedicated to thread A
    Choose a different thread to yield to (in our case, this is thread B)
    Change stack pointer to the stack pointer that was saved for thread B
    Restore registers
}

That's right, a thread context switch, in essence, simply means switching the stack pointer to a different stack. The key effect of this is that the return address on the stack is now no longer the one that was put on the stack when thread A called yield(); instead, the return address is the one that thread B put on the stack the last time it called yield(). So when yield() returns, it returns to wherever thread B was the last time it yielded control of the CPU.

Pretty funky, huh? It takes a moment to get your head wrapped round it.

If you want to extend this cooperative multitasking to preemptive multitasking, then all you have to do in principle is create an interrupt that gets called at regular intervals by a timer; the interrupt service routine for this interrupt is simply yield().

Real implementations have a lot more details to take care of, but in principle, this is all there is to thread context switches -- it really just means switching stacks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜