0

I am implementing a user-level thread lib using ucontext_t. I am linking threads to the scheduler thread via uc_link, however, we need to get the return value on some occasions. I don't know how to get the return value as the contexts are separate. The only way I can think of accessing the return value is by somehow going to the stack of that context and finding where the return value would be. However, this seems like a formula for disaster and weird errors.

beans
  • 31
  • 5
  • What return value? The entry-point function set via `makecontext()` returns `void`, so it has no return value. You reap undefined behavior if you instead pass a function that returns a value. – John Bollinger Mar 03 '22 at 15:26
  • Also, what does pthreads have to do with this? Writing your own thread library implies that you are *avoiding* pthreads. – John Bollinger Mar 03 '22 at 15:59
  • I meant that whatever function the thread may execute may want to return a value and if there was a way of capturing that value. However, I see that it is not possible – beans Mar 03 '22 at 17:30

1 Answers1

1

Get return value from ucontext as it terminates

An execution context such as is represented by ucontext_t has no return value. This is implicit in the behavior when the entry-point function terminates (the successor context, if any, is activated), and explicit in the signature of the entry-point function (it returns void).

Note also that the entry-point function must additionally be non-variadic, unlike makecontext() itself, though it can take any fixed number of arguments. The caller of makecontext is obligated to specify the correct argument count and that many int arguments.

If you want to communicate data between contexts then you should write it or a pointer to it in some shared memory location from which you can later, in a different context, retrieve it. Presumably, in this case that would be somewhere in the metadata that your lib maintains for each thread.

If the data in question are the return value of some function, then that function cannot be the context's entry-point. In that case (and for other reasons, too) you may want to avoid using functions provided by the user as ucontext entry points. Instead, use a function provided internally by the library that knows how to bootstrap to the user function and what to do when it returns.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157