Answer the question
In order to leave comments, you need to log in
How to make multiple threads wait?
Hello. There are multiple threads. In some places, they need to be stopped by an event from, let's say, a control thread, so that they wait for another event. How to do this?
Here is an example code:
Workflow:
doAny1();
doAny2();
lock.awaitIfLocked();
doAny3();
doAny4();
lock.awaitIfLocked();
...
lock.lock();
doAny();
lock.unlock();
Answer the question
In order to leave comments, you need to log in
This can be implemented via ReentrantReadWriteLock . The control thread captures writeLock, and the worker threads at the breakpoint capture readLock (for the duration of some action, I guess). They can acquire readLock all at the same time, but only if writeLock is not captured.
I really don't know why you just stop threads. Typically, there is a need to stop threads before doing something that needs to be protected. If you just have a stop without protecting the next action, then imagine this option:
1. The lock is free.
2. The worker thread jumps over the breakpoint.
3. Immediately after that, the OS switches control to the control thread.
4. The control thread acquires the lock.
5. The OS switches control back to the worker thread.
6. The worker thread executes the code behind the breakpoint (the lock is captured in the control thread).
Now tell me how this result differs from how if the worker thread just jumped the breakpoint while acquiring the lock?
Ideally read about Mutex/Semaphore.
Not ideally, make the necessary straights for these streams. For example, you declare the n-th number of Boolean variables that will add up the blocking of one or another or all threads. Well, with the usual branching you check this Lock / unlock
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question