Go: Story of TryLock Function
ℹ️ This article is based on Go 1.18.
Go 1.18 comes with a new function TryLock
(for the mutexes sync.Mutex
and sync.RWMutex
) that allows the developer to try acquiring a lock in a non-blocking mode, i.e. if the lock is already acquired, the function will simply return the boolean false
rather than waiting for the lock to be released.
This function piqued my curiosity because, although its name is explicit, its use cases are not obvious. Let’s collect information about it to better understand its usage.
Workflow
To better understand the workflow of a mutex, I suggest you read my article “Go: Mutex and Starvation.”
The lock of a mutex is not available if:
- 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.
In either of these cases, the function TryLock
will immediately return false
. Here is a diagram that summarizes those two use cases: