concept mutex in category go

appears as: mutex, Mutex, A mutex
Get Programming with Go

This is an excerpt from Manning's book Get Programming with Go.

Listing 31.1. Locking and unlocking a mutex: mutex.go
package main

import "sync"                                               #1

var mu sync.Mutex                                           #2

func main() {
    mu.Lock()                                               #3
    defer mu.Unlock()                                       #4
    // The lock is held until we return from the function.
}

With a small and well-defined piece of state to guard, a mutex is quite straightforward to use and is an essential tool when writing methods that you want to be usable from multiple goroutines at once.

A mutex is good to use for simple shared state, but it’s not uncommon to want something more. In the gopher factory of lesson 30, we might want gophers that act independently, responding to requests from other gophers but also doing their own thing over time. Unlike the gophers on the assembly line, gophers like this don’t respond entirely to messages from other gophers, but can decide to do things on their own behalf.