登录
首页 >  Golang >  Go问答

通过接口避免 goroutine 范围内的数据竞争

来源:stackoverflow

时间:2024-04-10 10:21:34 190浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《通过接口避免 goroutine 范围内的数据竞争》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我有以下 for...range 块,它使用 goroutine 调用 url。

func callUrls(urls []string, reqBody interface{}) []*Response {
    ch := make(chan *Response, len(urls))
    for _, url := range urls {
        somePostData := reqBody //this just seems to copy reference, not a deep copy
        go func(url string, somePostData interface{}) {
            //serviceMutex.Lock()
            //defer serviceMutex.Unlock()
            somePostData.(map[string]interface{})["someKey"] = "someval" //can be more deeper nested
            //Data race - while executing above line it seems the original data is only getting modified, not the new local variable

            //http post on url,
            postJsonBody, _ := json.Marshal(somePostData)
            req, err := http.NewRequest("POST", url, bytes.NewBuffer(postJsonBody))
            req.Header.Set("Content-Type", "application/json")
            req.Header.Set("Connection", "Keep-Alive")

            client := &http.Client{
                Timeout: time.Duration(time.Duration(300) * time.MilliSecond),
            }

            response, err := client.Do(req)
            response.Body.Close()


            // return to channel accordingly
            ch <- &Response{200, "url", "response body"}

        }(url, somePostData)
    }
    //for block to return result.
}

每个 goroutine func 都需要将修改后的 post 数据发布到 url。

但是,使用 -race 运行会在修改后数据接口的行显示数据争用。

我还尝试了 sync.mutex lock()unlock() 但它似乎阻止了整个应用程序。我不想使用 []bytes,因为修改切片似乎会消耗更多的 cpu(在我看来)。

避免数据竞争的最佳方法是什么?此外,连接似乎也没有被重用,导致 http 错误。有什么建议吗?


解决方案


几个选项:

使用互斥体

这是最安全、最直接的。看来您的 mutex 的范围可以缩小为:

servicemutex.lock()
somepostdata.(map[string]interface{})["somekey"] = "someval" 
postjsonbody, _ := json.marshal(somepostdata)
servicemutex.unlock()

这应该会对您的吞吐量有很大帮助。

让每个 goroutine 构建自己的 somepostdata

根据您的数据结构,这应该允许每个 goroutine 不与任何其他 goroutine 共享数据,并为您带来安全性和速度提升。想象一下,您不是传递一个可能包含大量引用的 interface{},而是传递一个能够构建请求正文的线程安全方法:

func callUrls(urls []string, buildReqBody func(...params...) interface{})
...


somePostData = buildReqBody(...params...)

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>