In what situations would one want to use reentrant locks versus normal locks?
The main difference between Simple/Regular Locks and Re-entrant Locks is that simple locks allow one thread to acquire a lock at a given point in time, keeping every other thread waiting, including the thread that holds the lock if it tried to lock again. Re-entrant locks allow the same thread to acquire a lock as many times as needed, provided that they already hold the lock, and keeps all other threads in a waiting queue for the same lock.
Re-entrant Locks are generally useful when recursion is needed. Imagine that you have a recursive function that needs to acquire a lock to execute. If you were using a simple lock, your first thread can easily deadlock itself. First iteration of the recursion will acquire the lock successfully, the second iteration will try to acquire the lock again, but will block forever. The second iteration will wait for the first iteration to unlock, but the first iteration will not unlock unless the second iteration completes.
A re-entrant lock is useful here because once a thread holds the lock, it can lock as many times as it pleases after that. Only catch is that your thread will have to unlock as many times as it locked, making it similar to a counting semaphore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With