Go 语言圣经 9.6 竞争条件检测 & 9.7 示例: 并发的非阻塞缓存

9.6 竞争条件检测

知识点

  • 1.Go的runtime和工具链为我们装备了动态分析工具–竞争检查器(the race detector)

9.7 示例: 并发的非阻塞缓存

知识点

  • 1.duplicate suppression(重复抑制/避免)

代码

  • 章节中的例子
func test_memoizing()  {
    m := memo.New(httpGetBody)
    for _, url := range incomingURLs() {
        start := time.Now()
        value, err := m.Get(url)
        if err != nil {
            log.Print(err)
        }
        fmt.Printf("%s, %s, %d bytes\n", url, time.Since(start), len(value.([]byte)))
    }
}
func test_memoizing_two()  {
    m := memo.New(httpGetBody)
    var n sync.WaitGroup
    for _, url := range incomingURLs() {
        n.Add(1)
        go func(url string) {
            start := time.Now()
            value, err := m.Get(url)
            if err != nil {
                log.Print(err)
            }
            fmt.Printf("%s, %s, %d bytes\n", url, time.Since(start), len(value.([]byte)))
            n.Done()
        }(url)
    }
    n.Wait()
}
func incomingURLs() []string  {
    URLs := []string{"https://golang.org","https://godoc.org","https://play.golang.org"}
    return  URLs
}
func httpGetBody(url string) (interface{}, error) {
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    return ioutil.ReadAll(resp.Body)
}
——不足之处,欢迎补充——

备注

《Go 语言圣经》

  • 学习记录所使用的GO版本是1.8
  • 学习记录所使用的编译器工具为GoLand
  • 学习记录所使用的系统环境为Mac os
  • 学习者有一定的C语言基础

代码仓库

猜你喜欢

转载自blog.csdn.net/liushihua147/article/details/81835838