On Sun, May 10, 2015 at 7:25 AM, josvazg <
jos...@gmail.com> wrote:
>
> I was surprised by sync lock behavior today:
>
> It seems sync.*Lock does not allow lock re-acquisition by the same goroutine
> that already has the lock.
>
> Why is that so?
A mutex implements an invariant. The invariant is true while the
mutex is not held. It's OK to break the invariant while the mutex is
held, as you update whatever state is protected by the mutex. You
must restore the invariant before you release the mutex.
If you re-acquire a mutex that you have already acquired, you can not
know the state of the invariant (if you do know, then you also know
that the mutex has already been acquired, and you have no need to
re-acquire it). Therefore, you can not safely modify the shared
state.
As a general rule, re-acquiring mutexes does not make sense. The C++
std::recursive_mutex type is a bad idea.
Ian