Back to course

Mutexes: Protecting Shared State

Go (Golang) for Cloud-Native Microservices

Mutual Exclusion

If two Goroutines try to write to the same map at once, Go will panic. Use a Mutex to lock access.

go type Counter struct { mu sync.Mutex value int }

func (c *Counter) Inc() { c.mu.Lock() defer c.mu.Unlock() c.value++ }

This ensures only one Goroutine can access the critical section at a time.