乐闻世界logo
搜索文章和话题

How do you use the "sync" package to protect shared data in Go?

1个答案

1

In the Go language, the sync package provides various synchronization primitives, such as mutexes, WaitGroup, and Condition variables (Cond), for synchronizing access to shared data across multiple goroutines. Below, I will focus on how to use sync.Mutex to protect shared data and prevent data races.

Using sync.Mutex to Protect Shared Data

A sync.Mutex is a mutex that ensures multiple goroutines do not access shared resources simultaneously, thereby avoiding race conditions. Mutexes have two primary methods: Lock() and Unlock(). Lock() is used to acquire the mutex, and Unlock() is used to release it.

Example Code

Assume a simple scenario where we need to increment a shared counter across multiple goroutines. Without using a mutex, multiple goroutines modifying the shared variable concurrently may lead to incorrect results.

go
package main import ( "fmt" "sync" ) func main() { var count int var lock sync.Mutex var wg sync.WaitGroup // Set up 10 goroutines for i := 0; i < 10; i++ { wg.Add(1) go func() { // Lock the shared variable in each goroutine lock.Lock() count++ lock.Unlock() wg.Done() }() } // Wait for all goroutines to complete wg.Wait() fmt.Println("Final count:", count) }

In this example, we create a shared variable named count and protect it using the lock from sync.Mutex. Each goroutine calls lock.Lock() before modifying count and lock.Unlock() after the modification. This ensures that only one goroutine can modify count at any time, thereby preventing race conditions.

Important Notes

  1. Ensure proper pairing of Lock and Unlock: Each Lock() call must be matched with a corresponding Unlock() call in the correct order.
  2. Avoid deadlocks: Ensure that locks are properly released in all execution paths to prevent deadlocks.
  3. Granularity of locks: Choosing the appropriate granularity for locks is crucial. Overly coarse lock granularity may reduce concurrency, while overly fine granularity may increase coding complexity and the chance of errors.

Using synchronization primitives from the sync package can effectively protect shared data in Go programs, preventing common data races and other concurrency errors.

2024年7月20日 03:24 回复

你的答案