Home >Backend Development >Golang >How Can I Safely Read Values from Multiple Goroutines in Go?
Reading Values Safely from Different Threads in Go
In Go, concurrent access to values from multiple goroutines without proper synchronization is dangerous. To ensure data integrity, it's crucial to employ synchronization mechanisms.
Synchronization with Mutexes and Read/Write Locks
In the given scenario, where the main thread needs to collect values from worker threads every 10 seconds, channels won't suffice. Instead, a read/write mutex can be used.
The workers will acquire a write lock when updating their values, while the main thread will acquire a read lock when retrieving values. This prevents race conditions and guarantees data consistency.
Example Implementation with Mutex
The following code exemplifies a simple implementation using a mutex:
type Worker struct { iterMu sync.RWMutex iter int } func (w *Worker) Iter() int { w.iterMu.RLock() defer w.iterMu.RUnlock() return w.iter } func (w *Worker) setIter(n int) { w.iterMu.Lock() w.iter = n w.iterMu.Unlock() }
Alternative: Using Atomic Counters
Alternatively, the sync/atomic package provides thread-safe atomic counters, allowing direct read and write operations without the overhead of mutexes.
type Worker struct { iter int64 } func (w *Worker) Iter() int64 { return atomic.LoadInt64(&w.iter) } func (w *Worker) setIter(n int64) { atomic.StoreInt64(&w.iter, n) }
The above is the detailed content of How Can I Safely Read Values from Multiple Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!