douxiangui5011 2018-05-16 05:22
浏览 46
已采纳

golang仅在作者进行更改时才阻止读者

I have one writer goroutine and multiple reader goroutines. I want to block readers when writer is changing data.

package main

data []int

func main() {
    m := sync.Mutex{}

    for i := 0; i< 10; i++ {
        go func reader() {
            for {
                m.Lock()
                myData := data
                m.Unlock()
                read_from_data(myData)
            }
        }()
    }

    go func writer() {
        for {
            newData := new_data()
            m.Lock()
            data = newData
            m.Unlock()
            time.Sleep(1 * time.Seconds)
        }
    }
}

How can i do this without readers blocking each other?

展开全部

  • 写回答

1条回答 默认 最新

  • dongzi3434 2018-05-16 05:26
    关注

    This is what sync.RWMutex is for.

    It has 2 different lock methods: RWMutex.Lock() for writers, and RWMutex.RLock() for readers. (And there are 2 different unlock methods, matching the different lock methods: RWMutex.Unlock() and RWMutex.RUnlock().)

    RWMutex allows multiple readers, or 1 writer. If a writer obtained the lock, no readers are allowed until the writer unlocks (also, no other writers allowed). If a reader obtains the read-lock, any other readers are allowed (but not a writer, not until all readers unlock).

    m := sync.RWMutex{}
    
    for i := 0; i < 10; i++ {
        go func() { // reader
            for {
                m.RLock()
                myData := data
                m.RUnlock()
                read_from_data(myData)
            }
        }()
    }
    
    go func() { // writer
        for {
            newData := new_data()
            m.Lock()
            data = newData
            m.Unlock()
            time.Sleep(1 * time.Seconds)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部