← All Exercises

Go Mutex Synchronization

advancedgo~25min

Background

Mutexes protect shared state in concurrent Go programs, preventing data races and ensuring consistency.

Problem

Implement a thread-safe counter using sync.Mutex with increment, decrement, and value methods, demonstrating proper lock/unlock.

Input

Concurrent calls to increment, decrement, and value from multiple goroutines.

Output

A consistent counter value reflecting all operations.

Sample tests

Sample 1

Input: 100 increments, 50 decrements
Expected: 50

Your solution

Learning objective

Learn mutex synchronization, the defer unlock pattern, and thread-safe data structure design.