// Personal website of Chris Smith

Snippets » Go » Mutex with context

A channel with a single buffered entry can be used as a mutex that respects context cancellation:

mutexChan := make(chan struct{}, 1)

select {
    case <-ctx.Done():
        // Handle context cancellation
    case mutexChan <- struct{}{}:
        defer func() { <- mutexChan }()
}

I first saw this pattern documented by Hal on h12.io.