liveBook · Manning

Try_lock

As explained in Learn Concurrent Programming with Go

TryLock is a Go mutex operation that acquires an available mutex immediately and returns false immediately when the mutex is unavailable.

TryLock is a non-blocking mutex operation. It acquires an available mutex and returns true; when another goroutine holds the mutex, it returns false immediately instead of blocking. section 4.1.3

Use TryLock deliberately:

  • Let a monitor goroutine inspect shared progress without adding contention; retry later when the mutex is busy. section 4.1.3
  • Unlock the mutex after a successful TryLock, just as with Lock; otherwise the protected critical section remains locked. section 4.1.3
  • Treat frequent use as a warning sign: ordinary goroutines are cheap to create, so another goroutine may be preferable to polling. section 4.1.3

Monitoring a frequency table

Several goroutines count letters from downloaded RFC pages while a monitor periodically calls mutex.TryLock(). On success it prints the frequency table and unlocks; on failure it reports that the mutex is busy and tries again later. The output therefore mixes completed downloads, updated counts, and occasional “Mutex already being used” messages.

How Learn Concurrent Programming with Go covers it

How deep it goes
Explains return values, retry behavior, contention trade-offs, and a monitoring example without developing the mutex implementation.
Examples
Uses a frequency-table monitor and exercises implementing TryLock for readers-writer mutexes and atomic spin locks.
What it assumes
Assumes mutex locking, unlocking, goroutines, and shared data; reinforces exclusive critical-section access and contention.
What you can do after
Apply it via Go's sync.Mutex to attempt immediate acquisition and choose whether to retry or perform other work.
How it connects
Connects mutexes, goroutines, critical sections, readers-writer mutexes, spin locks, and atomic variables.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.