I’m writing a thread process using semaphores.
Given K, I want to be able to check if all previous threads have entered the critical section at least K-1 times. If not, the current thread would block until the previous threads have been able to do so.
Example: if you set K = 3, when the current thread wants to enter the critical section, it must check if all previous threads have entered the critical section K-1 (so twice in this case) times before it can enter the critical section
Does anyone know of a way in which I can implement this in Java? Thanks in advance.
Make sure you are using Java 7 and use a Phaser. The Phaser accomplishes this out of the box, where K-1 will be the phase.
Here is an example:
So when starting there will be
nregistered parties in the phaser. Each time one threadarriveAndAwaitAdvanceit will wait until all threads reach that barrier. Once all threads reach that barrier the phase will increment. Once the phase reaches K-1 the invoking thread will break out.After
phaser.awaitAdvance(waitForPhase);your last statement is satisfiedEdit:
awaitAdvance(int phase)will suspend the current thread until the Phaser’s current phase is the phase passed in as the argument. Once all threads arrived and increments to the phase number passed in the current thread will be signaled to awake.