how we can solve a barrier problem which is a thread synchronization mechanism u
ID: 3684970 • Letter: H
Question
how we can solve a barrier problem which is a thread synchronization mechanism using SEMAPHORES.Implemeting the Barrier interface which recieves the number of threads it is intended to synchronize.and Worker threaded class that is passed the worker’s id, an object barrier of BarrierImpl, and an array, task, of 10 randomly generated integers where the ith integer corresponds to the time needed by the worker to finish task i. A Worker thread displays its current states which is one of the following: performing task I; waiting at the barrier; finished all tasks
in java please
Explanation / Answer
Hi below i have given the idea for your reference,
An interface for a barrier appears as follows:
public interface Barrier
{
/** * Each thread calls this method when it reaches
* the barrier. All threads are released to continue
* processing when thelast thread calls this method.
*/
public void waitForOthers();
/**
* Release all threads from waiting for the barrier.
* Any future calls to waitForOthers() will not wait
* until the Barrier is set again with a call
* to the constructor.
*/
public void freeAll();
}
The following code segment establishes a barrier and creates 10 Worker threads that will synchronize according to the barrier:
public static final int THREAD COUNT = 10;
Barrier jersey = new BarrierImpl(THREAD COUNT);
for (int i = 0; i < THREAD COUNT; i++)
(new Worker(jersey)).start();
Note that the barrier must be initialized to the number of threads that are being synchronized and that each thread has a reference to the same barrier object—jersey. Each Worker will run as follows:
// All threads have access to this barrier
Barrier jersey;
// do some work for a while . . .
// now wait for the others jersey.waitForOthers();
// now do more work . . .
When a thread invokes the method waitForOthers(), it will block until all threads have reached this method (the barrier). Once all threads have reached the method, they may all proceed with the remainder of their code. The freeAll() method bypasses the need to wait for threads to reach the barrier; as soon as freeAll() is invoked, all threads waiting for the barrier are released.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.