views:

321

answers:

2

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 main after create.

How do i get this address?

+1  A: 

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...

asveikau
A: 

You can possibly pull it off the stack with a deliberately "bad" subscript, but how are you going to switch stacks? This is possible, sometimes, without assembly, but then it's somehow worse.

DigitalRoss