Question: Is it possible to guarantee code execution in only one thread in a multithreaded program? (Or something that comes close to this)
In particular: I have a controller M (which is a thread) and threads A, B, C. I would like M to be able to decide who is allowed to work. When the flow is completed (permanently or temporarily), control transfers back to M.
Why: Ideally, I want A, B, and C to execute their code in their thread, while others do not start. This will allow each thread to keep a pointer and a stack of instructions during a pause, starting from where they left off when the controller returns them.
What I'm doing now: I wrote code that can really do this, but I don't like it.
In pseudo-C:
//Controller M
//do some stuff
UnlockMutex(mutex);
do{}while(lockval==0);
LockMutex(mutex);
//continue with other stuff
//Thread A
//The controller currently has the mutex - will release it at UnlockMutex
LockMutex(mutex);
lockval=1;
//do stuff
UnlockMutex(mutex);
Reason for which
do{}while(lockval==0);
when the mutex is unlocked, both A and M must continue. This hack ensures that A does not unlock the mutex before M can lock it again, so that A will brake the lock again and restart (it should only start once).
Still seems redundant, but does the job. So my question is: is there a better way?
source
share