Reputation: 83
Can anyone explain how to program Countdown latch with semaphores as the only synchronization primitive which are permitted to use.? Thanks.
Upvotes: 0
Views: 478
Reputation: 650
The countdown latch allows you to wait on the latch until it's current count is reduced to zero. THis means you can have a thread wait until a certain amount of work is completed by other threads, each one counting down when they are done doing whatever it is.
The semaphore allows you to allocate permits to tasks. You might only want 10 permits to be available, so the 11th task asking for a permit has to wait until another task returns one back.
So you could, for example, have a semaphore with only 1 permit available, and locking on that. This will result in the same behaviour as synchronizing the method/block. Once the permit is returnded, another thread can obtain it in order to enter the locked block.
sem.acquire();
doSomeStuff();
sem.release();
if the semaphore is initialised with only 1 permit, then it's the same as:
synchronized(someLock) {
doSomeStuff();
}
Upvotes: 0