开发者

Making a user space thread library with pthread, how do you properly create the first thread? (well first 2 threads)

So im making a user space thread library. lets say theres some program that uses it.

in that program it starts at the main method. before any calls to create_thread, there are no threads active.

then when the first thread is created, the library makes 2 threads. One for 'main' and one for the actual new thead you are making. This is the key step to running in parallel.

One thing I need to make this work is assign a pointer in each thread object I make to the next line of code that should be run when the thread starts. For the thread I create this is easy, it is a pointer to the function.

For the 'main' thread, this should point to the next line of code in开发者_如何学C main after create.

How do i get this address?


This is platform specific, usually based on some CPU register. If memory serves me correctly, typically on x86 with a sane calling convention this is something like [ebp + 4]. But as you might be able to tell, this is highly dependent on CPU and calling convention. In PowerPC, for example, it's stored in something called the "link register"... You can get stuff like this using inline asm.

Keep in mind you'll have to restore the stack to where it was as well... A user space (or kernel for that matter) implementation of threads will typically store a stack pointer for each context, and when it's time to context switch you can do something like the x86 instruction pushad (save all registers to stack) and swap stack pointers and restore any other state you need. Then you do something like popad and jump back to where you were before. (maybe with the ret instruction; in an interrupt routine this would be iretd)

But note in an interface like pthread_create(), what you are calling the "main thread" is rather implicit... That routine creates a new thread and tells it to start at some particular routine, and the guy returning from that is the "main thread" in your case. You might find that model a bit less of a headache than having your thread create routine explicitly insert something with <eip, esp> (return instruction ptr, stack ptr) into some list of threads...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜