Problem:
In Go, how can data be safely read from separate threads in parallel computing? Specifically, how can data be collected from worker threads without compromising data integrity?
Scenario:
The main thread creates multiple worker instances that run asynchronously. Every 10 seconds, the main thread needs to collect values (e.g., iteration counts) from the workers and display a consolidated report.
Question:
Is it safe to directly read values from the workers? Additionally, are there alternative approaches for implementing this requirement efficiently?
Answer:
Directly reading values from workers is unsafe because it violates Go's concurrency model. In Go, data shared between goroutines must be protected with synchronization mechanisms to prevent data corruption from simultaneous write operations.
To address this, one approach is to use the sync.RWMutex data structure:
Example implementation using sync.RWMutex:
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() }
Alternatively, the sync/atomic package offers atomic operations that ensure thread-safe access to shared variables. Example implementation using sync/atomic:
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) }
By utilizing these methods, both approaches provide a robust solution for reading values from separate threads while maintaining data integrity.
The above is the detailed content of How to Safely Read Shared Data from Parallel Go Routines?. For more information, please follow other related articles on the PHP Chinese website!