关于go:Go十大常见错误第7篇不使用race选项做并发竞争检测

7次阅读

共计 2026 个字符,预计需要花费 6 分钟才能阅读完成。

前言

这是 Go 十大常见谬误系列的第 7 篇:不应用 -race 选项做并发竞争检测。素材来源于 Go 布道者,现 Docker 公司资深工程师 Teiva Harsanyi。

本文波及的源代码全副开源在:Go 十大常见谬误源代码,欢送大家关注公众号,及时获取本系列最新更新。

背景

并发编程里很容易遇到并发拜访抵触的问题。

Go 语言里多个 goroutine 同时操作某个共享变量的时候,如果一个 goroutine 对该变量做写操作,其它 goroutine 做读操作,假如没有做好并发访问控制,就容易呈现并发拜访抵触,导致程序 crash。

大家能够看如下的代码示例:

package main

import ("fmt")

func main() {c := make(chan bool)
    m := make(map[string]string)
    go func() {m["1"] = "a" // First conflicting access.
        c <- true
    }()
    m["2"] = "b" // Second conflicting access.
    <-c
    for k, v := range m {fmt.Println(k, v)
    }
}

下面的代码会呈现并发拜访抵触,2 个 goroutine 同时对共享变量 m 做写操作。

通过 -race 选项,咱们就能够利用编译器帮咱们疾速发现问题。

$ go run -race main.go 
==================
WARNING: DATA RACE
Write at 0x00c000074180 by goroutine 7:
  runtime.mapassign_faststr()
      /usr/local/opt/go/libexec/src/runtime/map_faststr.go:202 +0x0
  main.main.func1()
      /Users/xxx/github/go-tutorial/workspace/senior/p28/data-race/main.go:11 +0x5d

Previous write at 0x00c000074180 by main goroutine:
  runtime.mapassign_faststr()
      /usr/local/opt/go/libexec/src/runtime/map_faststr.go:202 +0x0
  main.main()
      /Users/xxx/github/go-tutorial/workspace/senior/p28/data-race/main.go:14 +0xcb

Goroutine 7 (running) created at:
  main.main()
      /Users/xxx/github/go-tutorial/workspace/senior/p28/data-race/main.go:10 +0x9c
==================
1 a
2 b
Found 1 data race(s)
exit status 66

常见问题

一个常见的谬误是开发者测试 Go 程序的时候,不应用 -race 选项。

只管 Go 语言设计的目标之一是为了让并发编程更简略、更不容易出错,但 Go 语言开发者还是会遇到并发问题。

因而,大家在测试 Go 程序的时候,应该开启 -race 选项,及时发现代码里的并发拜访抵触问题。

$ go test -race mypkg    // to test the package
$ go run -race mysrc.go  // to run the source file
$ go build -race mycmd   // to build the command
$ go install -race mypkg // to install the package

举荐浏览

  • Go 十大常见谬误第 1 篇:未知枚举值
  • Go 十大常见谬误第 2 篇:benchmark 性能测试的坑
  • Go 十大常见谬误第 3 篇:go 指针的性能问题和内存逃逸
  • Go 十大常见谬误第 4 篇:break 操作的注意事项
  • Go 十大常见谬误第 5 篇:Go 语言 Error 治理
  • Go 十大常见谬误第 6 篇:slice 初始化常犯的谬误
  • Go 面试题系列,看看你会几题?
  • Go 编译器的 race detector 能够发现所有的并发抵触么?

开源地址

文章和示例代码开源在 GitHub: Go 语言高级、中级和高级教程。

公众号:coding 进阶。关注公众号能够获取最新 Go 面试题和技术栈。

集体网站:Jincheng’s Blog。

知乎:无忌。

福利

我为大家整顿了一份后端开发学习材料礼包,蕴含编程语言入门到进阶常识(Go、C++、Python)、后端开发技术栈、面试题等。

关注公众号「coding 进阶」,发送音讯 backend 支付材料礼包,这份材料会不定期更新,退出我感觉有价值的材料。还能够发送音讯「进群」,和同行一起交流学习,答疑解惑。

References

  • https://itnext.io/the-top-10-…
  • https://go.dev/doc/articles/r…
  • https://medium.com/@val_delep…

本文由 mdnice 多平台公布

正文完
 0