← All Exercises

Mutex for Shared State

intermediatego~20min

Background

Mutexes prevent data races when multiple goroutines access shared mutable state.

Problem

Protect a shared counter with mutex when multiple goroutines increment it concurrently.

Input

Shared counter with goroutines

Output

Race-free counter increments

Sample tests

Sample 1

Input: 1000 goroutines incrementing
Expected: counter = 1000

Your solution

Learning objective

Learn thread safety and synchronization primitives