So, to fix it I need during switch of context to non-local thread (setcontext() or even longjump() functions) I should update these data to current running stack.
user level switching is only valid within the same thread. The only way to do this is to do a local user level switch to a user level thread that immediately blocks the os level thread and wakes the os level thread, that is blocked in the same procedure and corresponds to the target user level thread. At wakeup that user level thread, which was blocked at the os level, reads the target user level thread and makes a local user level switch to it. The Mutex on which the user level threads blocks (at least its address) needs to be part of the context.
probably I give a wrong picture of operations 1. I run arbitrary function with stack associated with first thread 2. I copy current context using getcontext and store it somewhere 3. I stop doing function from 1, by switching to another function/stack associated with thread 1 4. after some time I create a new os thread and run some code inside it 5. then inside 2 thread I take old context from 2 above and perform setcontext from inside 2 thread to replace current function with state in the thread to the first one
So, I don’t need mutexes and wait for something - I have a time gap between suspend of function in os 1 and it continuation on thread 2. during continuation I already switched to thread 2… just need to associate old stack with it (it contains state of function/stack from 1)