Understanding the mutex.TryLock return false when the mutex is unlocked based on the memory model

452 views
Skip to first unread message

Benz

unread,
Sep 8, 2022, 8:04:47 AM9/8/22
to golang-nuts

There are two cases in mutex.TryLock could return false

  • the lock is currently held by another goroutine.
  • the lock is not held but the mutex is in starvation mode; i.e., the lock will be handed off to the next waiter.

However, Per The Go memory model

> As far as the memory model is concerned, l.TryLock (or l.TryRLock) may be considered to be able to return false even when the mutex l is unlocked.

I am confused about the above sentence. How to understand the mutex.TryLock returns false even when the mutex is unlocked based on the memory model in Go?

Ian Lance Taylor

unread,
Sep 8, 2022, 9:51:56 AM9/8/22
to Benz, golang-nuts
The memory model is defining when one event is synchronized before
another. That sentence is saying that in a sequence Lock -> Unlock ->
TryLock -> Lock there is no promise that the TryLock is synchronized
before the Lock. The TryLock can fail to lock the mutex even though
the mutex is unlocked.

Ian
Reply all
Reply to author
Forward
0 new messages