开发者

pthreads, setjmp, longjmp. How can you tell when a function is finished running?

I am writing 开发者_C百科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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜