Reentrant Locks: Pros and Cons?

In what situations could reentor locks be used compared to conventional locks?

+6
source share
2 answers

I assume that a reentrant lock will have an extra overhead compared to a regular lock - to check which thread gets the lock.

Therefore, if you know that during normal operation the thread will only receive a lock once before releasing it again, you can get some performance using a regular lock. This can be especially useful in hard loops, etc.

+5
source

The main difference between plain / regular locks and repeat locks is that simple locks allow one thread to get a lock at a specific point in time, keeping every other thread, including a thread that holds the lock, if it tries to lock again. Re-entry locks allow the same thread to obtain a lock as many times as necessary, provided that they already hold the lock and keep all other threads in the waiting queue for the same lock.

Re-entry captures are usually useful when recursion is required. Imagine you have a recursive function that needs to get a lock to execute. If you used a simple lock, your first thread can easily slow down. The first iteration of recursion will be completed successfully, the second iteration will try to get the lock again, but will be locked forever. The second iteration will wait for the first iteration to unlock, but the first iteration will not be unlocked if the second iteration does not complete.

Re-entry locking is useful here because, as soon as the thread holds the lock, it can block as many times as after that. Just catch that your thread will have to unlock as many times as it is blocked, which makes it look like a counting semaphore.

+8
source

Source: https://habr.com/ru/post/892414/


All Articles