Reputation: 1600
I am trying to implement a user level thread library . Getcontext function is used to save the context of the current thread in memory . The function Getcontext are used in 2 cases
But, in both cases, it returns the same value. So, how do i differentiate between these 2 cases ?
Thanks
Upvotes: 4
Views: 2836
Reputation: 229138
getcontext does not move to a new thread, setcontext() and swapcontext() does. Your thread library should implement at least these 2 features:
Ability to create a new thread.
Ability to switch to another thread.
In the first case, you call getcontext() to initialize a ucontext_t , allocate memory for a stack and set the stack pointer in the ucontext_t, then you call makecontext() to initialize the context with a starting function.
In the second case, you call getcontext() to store the context for the current thread, and setcontext() to switch to another thread you have previously stored. Or, more commonly, you'd use swapcontext combine the get/setcontext calls. See e.g. here for a very simple way of implementing cooperative threads with get/setcontext.
Upvotes: 10