2
int swapcontext(ucontext_t *oucp, ucontext_t *ucp);
int getcontext(ucontext_t *ucp);
int setcontext(const ucontext_t *ucp);

If my understanding is correct, swapcontext is equivalent to first calling getcontext on oucp and then calling setcontext on ucp. I am trying to see how I could implement swapcontext with getcontext and setcontext.

int swapcontext(ucontext_t *oucp, ucontext_t *ucp)  
{  
    getcontext(oucp);  
    setcontext(ucp);  
}

The problem is that the context of oucp is at the wrong line, I want to call getcontext in a way such that the next line is the line after setcontext(ucp). However, setcontext does not return so I cannot do that. Moreover, if I implement swapcontext in this manner, if I pass the same arguments to oucp and ucp I will be stuck.

How would one implement swapcontext using these two functions? Or is it not possible?

John Smith
  • 43
  • 4

2 Answers2

4

Here's one way to do it. The idea is to set a boolean variable when setcontext() is called for the first time, so that the second time getcontext() returns, you can skip the setcontext() call.

int swapcontext(ucontext_t *oucp, ucontext_t *ucp) {
    volatile bool swapped = false;
    int result = getcontext(oucp);
    if (result == 0 && !swapped) {
        swapped = true;
        result = setcontext(ucp);
    }

    return result;
}
gsgx
  • 12,020
  • 25
  • 98
  • 149
1

Ran into this problem when reviewing for an exam! Just an idea to increment the count when swapping back to the old context.

int swapcontext(ucontext_t* old_ucp, ucontext_t* new_ucp) {
  volatile int count = 0;
  getcontext(old_ucp);
  count++;
  if (count == 1) {
    setcontext(new_ucp);
    /* Unsuccessful? return -1 */
    return -1;
  }
  if (count == 2) {
    /* The saved context is restored, return 0 */
    return 0;
  }
}
tngh
  • 11
  • 4
  • Definitely needs [`volatile`](https://en.cppreference.com/w/cpp/language/cv) as in gsgx's answer. Without that, the optimizer sees `int count = 0; count++;` and concludes that `count == 1` always because it doesn't know about time travel. – Khuldraeseth na'Barya Jun 21 '23 at 01:03
  • Hmmmm okii, edited. Thank you :) – tngh Jun 21 '23 at 01:16