Перейти к содержимому

Mutex Basics in Go

0:00 / 0:00

Mutex Basics in Go

427
427
Welcome to Go Bytes - Learn Go one step at a time. Code examples, challenges, and real learning. Goroutines can run at the same time, but when they update the same variable you get race conditions and wrong results. In this Go Byte, you will learn how sync.Mutex protects shared state with Lock and Unlock, and why defer Unlock is a common pattern. What You'll Learn: - Why counter-style updates are not atomic and how races happen - How a mutex lets only one goroutine run a critical section at a time - The Lock and Unlock pattern and using defer to always release the lock - When a mutex fits better than channels for protecting shared data Conceptual Explanation: A mutex is a mutual exclusion lock. Only one goroutine can hold the lock at a time. You call Lock before reading or writing shared data, then Unlock when done. If two goroutines try to increment a counter without a mutex, both can read the same value and one update can be lost. With a mutex, updates happen one after another so the counter stays correct. defer Unlock after Lock avoids forgetting to unlock on every path. How It Fits: Mutexes are standard when several goroutines share memory, for example counters, maps, or structs. Channels are great for passing data between goroutines; mutexes are often simpler when you only need to guard shared state. This builds on goroutines and WaitGroup. Key Takeaways: - Shared writes without coordination can cause race conditions - sync.Mutex protects a critical section with Lock and Unlock - defer mu.Unlock() after Lock helps prevent deadlocks from missed unlocks - Use a mutex when multiple goroutines access the same data - Channels suit communication; mutexes suit protecting shared memory Try the challenge from the video before checking the solution. Links: Lesson folder on GitHub: https://github.com/GaryClarke/go-bytes/tree/main/mutex-basics Build your first Go app with me: https://www.garyclarke.tech/p/build-your-first-go-app Join the mailing list for new lessons and resources: https://content.garyclarke.tech/go-bytes-signup Follow on X/Twitter: https://twitter.com/garyclarketech Connect on LinkedIn: https://www.linkedin.com/in/garyclarketech/ Subscribe for more Go lessons. #golang #go #programming #coding #learnprogramming #gobytes