Home > Back-end >  Several locks in one thread, why might they be needed?
Several locks in one thread, why might they be needed?

Time:04-05

It says here :

While a lock is held, the thread that holds the lock can again acquire and release the lock.

Question. For what purpose can several consecutive locks be used in one thread? Or does it give nothing, but the article says to clarify that inside one thread the code in the second lock will also be executed because the lock is used in the same thread?

I just want to understand the purpose of this information.

CodePudding user response:

Its called recursive locking. It is useful if you have complex paths that may end up trying to lock a resource twice (like in a recursive function). It saves you have to keep track of whether or not you already have a lock.

It is typically implemented as a counter, after the first lock subsequent locks just increment the counter, unlocks decrement, when the count reaches 0 the mutex is released

  • Related