Reading values from a different thread

十年热恋 提交于 2019-11-29 12:03:54

In Go no value is safe for concurrent access from multiple goroutines without synchronization if at least one of the accesses is a write. Your case meets the conditions listed, so you must use some kind of synchronization, else the behavior would be undefined.

Channels are used if goroutine(s) want to send values to another. Your case is not exactly this: you don't want your workers to send updates in every 10 seconds, you want your main goroutine to fetch status in every 10 seconds.

So in this example I would just protect the data with a sync.RWMutex: when the workers want to modify this data, they have to acquire a write lock. When the main goroutine wants to read this data, it has to acquire a read lock.

A simple implementation could look like this:

type Worker struct {
    iter    int
    iterMux sync.RWMutex
}

func (w *Worker) Iter() int {
    w.iterMux.RLock()
    defer w.iterMux.RUnlock()
    return w.iter
}

func (w *Worker) setIter(n int) {
    w.iterMux.Lock()
    w.iter = n
    w.iterMux.Unlock()
}

func (w *Worker) incIter() {
    w.iterMux.Lock()
    w.iter++
    w.iterMux.Unlock()
}

Using this example Worker, the main goroutine can fetch the iteration using Worker.Iter(), and the worker itself can change / update the iteration using Worker.setIter() or Worker.incIter() at any time, without any additional synchronization. The synchronization is ensured by the proper use of Worker.iterMux.

Alternatively for the iteration counter you could also use the sync/atomic package. If you choose this, you may only read / modify the iteration counter using functions of the atomic package like this:

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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!