Can a C++ thread A suspend its execution by storing that "pause" P in an object that can then be used in another thread B to run a function F in thread A?
B could use P to unlock a mutex owned by A. Or F could lock a recursive mutex that was already locked by A, which is can be done safely (as safely as only recursive locking scheme when you have call backs) because:
- the process is purely cooperative
- real A isn't running while F run be B runs "in A", so only one execution has the lock
[Of course it's patently unsafe when done in a disorderly way, exactly like any recursive lock held while doing arbitrary call backs (that don't know the lock is already held and misinterpret being able to lock, thinking the mutex wasn't locked) or non recursive mutexes (might try to lock an already locked mutex and deadlock or cause an error), or essentially any scenario involving wait for a ressource in a call back called with a lock.]
Because a thread cannot run in parallel with itself, A would could only restart once P is destroyed.
The point here is that the OS shouldn't get involved, only the C++ runtime: F would run immediately in OS thread B, not be scheduled for execution. The OS thread B would still be running, but executing as thread A.
In other words, can C++ threads exchange identity in a cooperative way?