登录
首页 >  Golang >  Go问答

协同多 goroutine 计数器同步

来源:stackoverflow

时间:2024-02-22 11:03:26 376浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《协同多 goroutine 计数器同步》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我有一个 golang 应用程序,可以浏览网站的页面,并且应该下载网站上的每个链接。它看起来有点像这样(我事先不知道页数,所以这是同步完成的):

page := 0
results := getpage(page)
c := make(chan *http.response)
for len(results) > 0 {
  for result := range results {
    go myproxyswitcher.downloadchan(result.url, c)
    fmt.println(myproxyswitcher.counter)
  }
  page++
  results = getpage(page)
  myproxyswitcher.counter++
}

不同的是,每 10 个请求,我想更改用于连接到网站的代理。为此,我创建了一个带有计数器成员的结构:

type proxyswitcher struct {
    proxies []string
    client  *http.client
    counter int
}

然后,每次从 downloadchan 发出请求时,我都会增加计数器。

func (p *proxyswitcher) downloadchan(url string, c chan *http.response) {
    p.counter++
    proxy := p.proxies[int(p.counter/10)%len(p.proxies]
    res := p.client.get(url, proxy)
    c <- res

}

当它进行下载时,计数器不会在 goroutine 之间同步。 如何在 goroutine 之间同步计数器的值?

我从这些 println 得到的结果是:

1
1
1
1
1
1
2
3
3
3
3
3
3
3
3
3
3
3
3
3
3
3
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
5
5
5

我期待着

1
2
3
4
5
...

正确答案


您的代码中有竞争条件。

在第一个代码片段中,您将修改“main”goroutine 中的 counter 字段:

  // ...
  myproxyswitcher.counter++

在第三个片段中,您还可以从不同的 goroutine 修改该计数器:

  // ...
  p.counter++

这是 go 中的非法代码。根据定义,结果是未定义的。要了解原因,您必须仔细阅读 Go Memory Model。提示:它可能不容易阅读。

要解决此问题,您需要确保同步。有很多方法可以做到这一点。

正如对您的问题的评论中所建议的,一种方法是使用互斥体。下面是一个示例,有点混乱,因为它需要对主循环进行一些重构。但这是同步对计数器的访问的方式:

type proxyswitcher struct {
  proxies []string
  client  *http.client
    
  mu sync.mutex
  counter int
}

func (p *proxyswitcher) downloadchan(url string, c chan *http.response) {
  p.mu.lock()
  p.counter++
  // gotta read it from p while holding
  // the lock to use it below
  counter := p.counter
  p.mu.unlock()

  // here you use counter rather than p.counter,
  // since you don't hold the lock anymore
  proxy := p.proxies[int(counter/10)%len(p.proxies)]
  res := p.client.get(url, proxy)
  c <- res
}

// ... the loop ...
for len(results) > 0 {
  for result := range results {
    go myproxyswitcher.downloadchan(result.url, c)
    
    // this is kinda messy, would need some heavier
    // refactoring, but this should fix the race:
    myproxyswitcher.mu.lock()
    fmt.println(myproxyswitcher.counter)
    myproxyswitcher.mu.unlock()
  }
  page++
  results = getpage(page)

  // same... it's messy, needs refactoring
  myproxyswitcher.mu.lock()
  myproxyswitcher.counter++
  myproxyswitcher.mu.unlock()
}

或者,您可以将该计数器更改为例如uint64,然后使用atomic/sync包执行goroutine安全操作:

type ProxySwitcher struct {
  proxies []string
  client  *http.Client
  counter uint64
}
func (p *ProxySwitcher) downloadChan(url string, c chan *http.Response) {
  counter := atomic.AddUint64(&p.counter, 1)

  // here you use counter rather than p.counter, since that's your local copy
  proxy := p.proxies[int(counter/10)%len(p.proxies)]
  res := p.client.Get(url, proxy)
  c <- res
}

// ... the loop ...
for len(results) > 0 {
  for result := range results {
    go myProxySwitcher.downloadChan(result.URL, c)
    counter := atomic.LoadUint64(&myProxySwitcher.counter)
    fmt.Println(counter)
  }
  page++
  results = getPage(page)

  atomic.AddUint64(&myProxySwitcher.counter, 1)
}

我可能会使用最后一个版本,因为它更干净,而且我们并不真正需要互斥体。

好了,本文到此结束,带大家了解了《协同多 goroutine 计数器同步》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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