Go Pattern: Context-aware Lock
We often use Mutex or RWMutex as locks in Go, but sometimes we need a lock that can be cancelled by a context during the lock attempt. The pattern is simple - we use a channel with length 1: lockChan := make(chan struct{}, 1) lockChan <- struct{}{} // lock <- lockChan // unlock When multiple goroutines try to obtain the lock, only one of them is able to fill into the only slot, and the rest are blocked until the slot is empty again after a readout. ...