Wk4L1 - Reentrant Locks and Semaphores Flashcards
What is a Lock in multithreading?
A lock is a mechanism that ensures only one thread can execute a critical section at a time, providing mutual exclusion. It guarantees the “happens-before” relationship, meaning all changes made before releasing the lock are visible to the next thread acquiring it.
What is a ReentrantLock?
A reentrant lock allows the same thread to acquire the lock multiple times in nested critical sections. It must be released with unlock() after the thread completes execution in the critical section.
What is the difference between a ReentrantLock and a Binary Semaphore?
ReentrantLock: A locking mechanism where the thread that obtains the lock owns it and must release it. The same thread can hold the lock multiple times.
Binary Semaphore: A signaling mechanism that allows threads to signal and acquire resources. The thread does not “own” the semaphore, and it can be released by another thread.
What are the advantages of using Locks?
- More flexible than synchronized methods.
- Can be used in complex algorithms where locks are acquired and released in varying orders.
- Support for nested critical sections with reentrant behavior.
What are Semaphores?
Semaphores are synchronization mechanisms that control access to a finite number of resources. They use a counter to track available resources. Threads use acquire() to decrease the count and release() to increase it.
What is a Counting Semaphore?
A counting semaphore allows a specified number of threads to access a resource simultaneously. The counter can be any positive value, with 0 indicating no more resources are available.
What is the main issue with using Locks?
Locks can cause performance issues since other threads are blocked or put into a waiting state, leading to expensive context switching.
How does a Semaphore differ from other mutual exclusion techniques like locks?
Semaphores allow multiple threads to access resources at the same time (in contrast to locks that allow only one thread). They are more flexible for managing resources like thread pools or queues.