Search code examples
cpthreadsposixcontext-switchstack-pointer

Where is The Value of the Current Stack Pointer Register Stored Before Context Switching In POSIX C Threads


If I were to use pthreads in POSIX environments, and a context switch is about to happen, the current value of the esp register has to be stored somewhere so I can retrieve it when I context switch back to this thread, as the esp register's value will be overwritten by another thread's saved SP value. I think it is impossible to have separate esp register for every thread (correct me if I am wrong). Having said that, I would like to know in what data structure the SP value of the current thread is stored right before the context switching is hit?

I tried looking up the struct pthread*'s value casted from the value of pthread_t, but nothing was changing when, say, I call a certain function to change the current SP of the thread I am testing (i.e. compare before and after calling the testing function).


Solution

  • This depends entirely upon how the Posix library is implemented. If the threads are implemented by the OS, the values of all registers are stored in the thread's [process] context block before a context switch.

    if the thread are implemented in a library, the registers have to be stored in some data structure managed by the library. Such a library implementation needs to save all the general registers but does not (and cannot) need to save the process-specific kernel registers.