Is Reading Values from Different Threads Safe?
In Go, safe concurrent access to values requires synchronization when multiple goroutines are involved, especially when at least one of them performs writes. In the given scenario, it's necessary to implement synchronization to safeguard against undefined behavior.
Recommended Approach: Utilizing Mutexes
Channels, although an option for message passing, may introduce unnecessary complexity due to the required synchronization for message retrieval in the main thread. Instead, it's recommended to employ read-write mutexes (sync.RWMutex). These locks protect data by enforcing lock acquisition for modify operations (workers) and read-only access for status retrievals (main thread).
Example Implementation
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() }
This approach ensures that workers modifying the iteration count acquire write locks, while the main thread reading the count acquires read locks.
Alternative: Atomic Operations
The sync/atomic package provides atomic operations that enable synchronization-free modification of specific data types, such as integers. It ensures integrity by restricting read and modify operations to its atomic functions.
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) } func (w *Worker) incIter() { atomic.AddInt64(&w.iter, 1) }
This approach offers a simpler synchronization mechanism, but note that it's only applicable for specific data types.
By adopting one of these methods, you can safely read values from workers in different threads, guaranteeing data integrity and avoiding undefined behavior.
The above is the detailed content of How to Safely Read Values from Different Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!