week 4 - explicit locks , semaphores Flashcards
(6 cards)
reentrant lock
reentrant locks allow same thread to aqquire a lock it already holds without causing a deadlock
reentrant lock vs non reentrant locks explanation
A reentrant lock is an explicit lock the programmer must manually lock() and unlock(), decoupling locking from synchronized methods or blocks.
Reentrant locks allow the same thread to acquire the same lock multiple times without blocking.
However, the programmer must ensure that each lock() call is matched by a corresponding unlock(), or the lock will never be fully released.
This prevents self-deadlock, a scenario where a thread blocks itself by trying to acquire a lock it already holds — something that can happen with non-reentrant locks.
In non-reentrant locks, if a thread tries to reacquire a lock it already holds, it blocks, but since it’s waiting on itself to release the lock, it never does.
This results in self-deadlock, and also blocks all other threads waiting on the same lock.
reentrant lock can be made to give threads the lock in the order they tried to obtain it
Lock lock = new ReentrantLock(true)
true ensures lock fairness
In a fair lock, threads acquire the lock in the order they attempted to obtain it (FIFO). In an unfair lock (default), order is not guaranteed
one way to fix deadlocks
“Ensure all threads acquire multiple locks in a consistent, fixed global order.”
removes circular wait usually caused when threads request locks in a different order
semaphores
A semaphore is a synchronization mechanism that uses an integer value to control how many threads can access a shared resource at the same time.
It starts with a fixed number of permits (e.g., 5). Each time a thread wants access, it must acquire a permit, which decreases the count.
If no permits are available (count is 0), the thread blocks until a permit is released.
Once the thread is done, it releases the permit, increasing the count and allowing another waiting thread to proceed.