CuriousCoder
CuriousCoder

Reputation: 1600

Question on Getcontext function

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

  1. To save the current context and move to the next thread
  2. To create a new context

But, in both cases, it returns the same value. So, how do i differentiate between these 2 cases ?

Thanks

Upvotes: 4

Views: 2836

Answers (1)

nos
nos

Reputation: 229138

getcontext does not move to a new thread, setcontext() and swapcontext() does. Your thread library should implement at least these 2 features:

  1. Ability to create a new thread.

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

Related Questions