views:

296

answers:

3

I am writing a user space thread library. I have a struct that manages each thread. My threads are very simple, they take a function ptr and its arguments, and just run that function one time.

Each thread has a jmp_buf and I use setjmp and longjmp to switch between threads. One thing I cant figure out is how to tell when this function is finished.

For each thread I modify the jmpbuf in 2 ways.

  1. I edit the PC and set it to the function pointer, so the program counter goes there next.
  2. I also make each one have its own stack and edit SP so it points to that stack

So using my thread control struct I can switch between threads and have each one maintain state, but do not know how to tell when that function is finished. When it is finished i want to call a special exit() function I have.

+1  A: 

You could modify the return address on the stack to point to your exit() function, or wrap the function call in another function that calls exit() after it.

Andrew Coleson
A: 

It'll try to return to wherever it was called from originally - presumably your create_thread function.

caf
+1  A: 

Instead of modifying your PC to the user function, you should actually be calling some special function (let's call it run_thread()) that branches to that thread's entry function. When that entry function returns (that is, the thread has exited), run_thread() should do whatever work is required to indicate that this thread is done (probably by removing that thread control block from the scheduling list and adding it to the join() cleanup list). It can then yield and when the parent calls join() on its ID, it will be cleaned up.

Variable Length Coder