Home > Backend Development > Golang > How to Safely Read Shared Data from Parallel Go Routines?

How to Safely Read Shared Data from Parallel Go Routines?

Barbara Streisand
Release: 2025-01-02 14:31:39
Original
361 people have browsed it

How to Safely Read Shared Data from Parallel Go Routines?

Reading Values from Shared Data in Parallel Go Routines

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:

  • Write locks: Acquired by workers when modifying shared data, ensuring exclusive access.
  • Read locks: Acquired by the main thread when reading shared data, allowing concurrent reads but preventing writes.

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()
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template