Data Race Detector 数据种类探测器:数据种类探测器手册

Introduction

Data races are among the most common and hardest to debug types of bugs in concurrent systems. A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write. See the The Go Memory Model for details.

Here is an example of a data race that can lead to crashes and memory corruption:

  1. func main() {
  2. c := make(chan bool)
  3. m := make(map[string]string)
  4. go func() {
  5. m["1"] = "a" // First conflicting access.
  6. c <- true
  7. }()
  8. m["2"] = "b" // Second conflicting access.
  9. <-c
  10. for k, v := range m {
  11. fmt.Println(k, v)
  12. }
  13. }

Usage

To help diagnose such bugs, Go includes a built-in data race detector. To use it, add the -race flag to the go command:

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

Report Format

When the race detector finds a data race in the program, it prints a report. The report contains stack traces for conflicting accesses, as well as stacks where the involved goroutines were created. Here is an example:

  1. WARNING: DATA RACE
  2. Read by goroutine 185:
  3. net.(*pollServer).AddFD()
  4. src/net/fd_unix.go:89 +0x398
  5. net.(*pollServer).WaitWrite()
  6. src/net/fd_unix.go:247 +0x45
  7. net.(*netFD).Write()
  8. src/net/fd_unix.go:540 +0x4d4
  9. net.(*conn).Write()
  10. src/net/net.go:129 +0x101
  11. net.func·060()
  12. src/net/timeout_test.go:603 +0xaf
  13.  
  14. Previous write by goroutine 184:
  15. net.setWriteDeadline()
  16. src/net/sockopt_posix.go:135 +0xdf
  17. net.setDeadline()
  18. src/net/sockopt_posix.go:144 +0x9c
  19. net.(*conn).SetDeadline()
  20. src/net/net.go:161 +0xe3
  21. net.func·061()
  22. src/net/timeout_test.go:616 +0x3ed
  23.  
  24. Goroutine 185 (running) created at:
  25. net.func·061()
  26. src/net/timeout_test.go:609 +0x288
  27.  
  28. Goroutine 184 (running) created at:
  29. net.TestProlongTimeout()
  30. src/net/timeout_test.go:618 +0x298
  31. testing.tRunner()
  32. src/testing/testing.go:301 +0xe8

Options

The GORACE environment variable sets race detector options. The format is:

  1. GORACE="option1=val1 option2=val2"

The options are:

  • log_path (default stderr): The race detector writes its report to a file named log_path.pid. The special names stdout and stderr cause reports to be written to standard output and standard error, respectively.
  • exitcode (default 66): The exit status to use when exiting after a detected race.
  • strip_path_prefix (default ""): Strip this prefix from all reported file paths, to make reports more concise.
  • history_size (default 1): The per-goroutine memory access history is 32K * 2**history_size elements. Increasing this value can avoid a "failed to restore the stack" error in reports, at the cost of increased memory usage.
  • halt_on_error (default 0): Controls whether the program exits after reporting first data race.

Example:

  1. $ GORACE="log_path=/tmp/race/report strip_path_prefix=/my/go/sources/" go test -race

Excluding Tests

When you build with -race flag, the go command defines additional build tag race. You can use the tag to exclude some code and tests when running the race detector. Some examples:

  1. // +build !race
  2.  
  3. package foo
  4.  
  5. // The test contains a data race. See issue 123.
  6. func TestFoo(t *testing.T) {
  7. // ...
  8. }
  9.  
  10. // The test fails under the race detector due to timeouts.
  11. func TestBar(t *testing.T) {
  12. // ...
  13. }
  14.  
  15. // The test takes too long under the race detector.
  16. func TestBaz(t *testing.T) {
  17. // ...
  18. }

How To Use

To start, run your tests using the race detector (go test -race). The race detector only finds races that happen at runtime, so it can't find races in code paths that are not executed. If your tests have incomplete coverage, you may find more races by running a binary built with -race under a realistic workload.

Typical Data Races

Here are some typical data races. All of them can be detected with the race detector.

Race on loop counter

  1. func main() {
  2. var wg sync.WaitGroup
  3. wg.Add(5)
  4. for i := 0; i < 5; i++ {
  5. go func() {
  6. fmt.Println(i) // Not the 'i' you are looking for.
  7. wg.Done()
  8. }()
  9. }
  10. wg.Wait()
  11. }

The variable i in the function literal is the same variable used by the loop, so the read in the goroutine races with the loop increment. (This program typically prints 55555, not 01234.) The program can be fixed by making a copy of the variable:

  1. func main() {
  2. var wg sync.WaitGroup
  3. wg.Add(5)
  4. for i := 0; i < 5; i++ {
  5. go func(j int) {
  6. fmt.Println(j) // Good. Read local copy of the loop counter.
  7. wg.Done()
  8. }(i)
  9. }
  10. wg.Wait()
  11. }

Accidentally shared variable

  1. // ParallelWrite writes data to file1 and file2, returns the errors.
  2. func ParallelWrite(data []byte) chan error {
  3. res := make(chan error, 2)
  4. f1, err := os.Create("file1")
  5. if err != nil {
  6. res <- err
  7. } else {
  8. go func() {
  9. // This err is shared with the main goroutine,
  10. // so the write races with the write below.
  11. _, err = f1.Write(data)
  12. res <- err
  13. f1.Close()
  14. }()
  15. }
  16. f2, err := os.Create("file2") // The second conflicting write to err.
  17. if err != nil {
  18. res <- err
  19. } else {
  20. go func() {
  21. _, err = f2.Write(data)
  22. res <- err
  23. f2.Close()
  24. }()
  25. }
  26. return res
  27. }

The fix is to introduce new variables in the goroutines (note the use of :=):

  1. ...
  2. _, err := f1.Write(data)
  3. ...
  4. _, err := f2.Write(data)
  5. ...

Unprotected global variable

If the following code is called from several goroutines, it leads to races on the service map. Concurrent reads and writes of the same map are not safe:

  1. var service map[string]net.Addr
  2.  
  3. func RegisterService(name string, addr net.Addr) {
  4. service[name] = addr
  5. }
  6.  
  7. func LookupService(name string) net.Addr {
  8. return service[name]
  9. }

To make the code safe, protect the accesses with a mutex:

  1. var (
  2. service map[string]net.Addr
  3. serviceMu sync.Mutex
  4. )
  5.  
  6. func RegisterService(name string, addr net.Addr) {
  7. serviceMu.Lock()
  8. defer serviceMu.Unlock()
  9. service[name] = addr
  10. }
  11.  
  12. func LookupService(name string) net.Addr {
  13. serviceMu.Lock()
  14. defer serviceMu.Unlock()
  15. return service[name]
  16. }

Primitive unprotected variable

Data races can happen on variables of primitive types as well (boolintint64, etc.), as in this example:

  1. type Watchdog struct{ last int64 }
  2.  
  3. func (w *Watchdog) KeepAlive() {
  4. w.last = time.Now().UnixNano() // First conflicting access.
  5. }
  6.  
  7. func (w *Watchdog) Start() {
  8. go func() {
  9. for {
  10. time.Sleep(time.Second)
  11. // Second conflicting access.
  12. if w.last < time.Now().Add(-10*time.Second).UnixNano() {
  13. fmt.Println("No keepalives for 10 seconds. Dying.")
  14. os.Exit(1)
  15. }
  16. }
  17. }()
  18. }

Even such "innocent" data races can lead to hard-to-debug problems caused by non-atomicity of the memory accesses, interference with compiler optimizations, or reordering issues accessing processor memory .

A typical fix for this race is to use a channel or a mutex. To preserve the lock-free behavior, one can also use thesync/atomic package.

  1. type Watchdog struct{ last int64 }
  2.  
  3. func (w *Watchdog) KeepAlive() {
  4. atomic.StoreInt64(&w.last, time.Now().UnixNano())
  5. }
  6.  
  7. func (w *Watchdog) Start() {
  8. go func() {
  9. for {
  10. time.Sleep(time.Second)
  11. if atomic.LoadInt64(&w.last) < time.Now().Add(-10*time.Second).UnixNano() {
  12. fmt.Println("No keepalives for 10 seconds. Dying.")
  13. os.Exit(1)
  14. }
  15. }
  16. }()
  17. }

Supported Systems

The race detector runs on darwin/amd64freebsd/amd64linux/amd64, and windows/amd64.

Runtime Overhead

The cost of race detection varies by program, but for a typical program, memory usage may increase by 5-10x and execution time by 2-20x.

28 Data Race Detector 数据种类探测器:数据种类探测器手册的更多相关文章

  1. 使用Spring Data ElasticSearch+Jsoup操作集群数据存储

    使用Spring Data ElasticSearch+Jsoup操作集群数据存储 1.使用Jsoup爬取京东商城的商品数据 1)获取商品名称.价格以及商品地址,并封装为一个Product对象,代码截 ...

  2. Spring Data:企业级Java的现代数据访问技术(影印版)

    <Spring Data:企业级Java的现代数据访问技术(影印版)>基本信息原书名:Spring Data:Modern Data Access for Enterprise Java作 ...

  3. 转:代码的坏味道之二十 :Data Class(纯稚的数据类)或POJO

    所谓Data Class是指:它们拥有一些值域(fields),以及用于访问(读写]这些值域的函数,除此之外一无长物.这样的classes只是一种「不会说话的数据容器」,它们几乎一定被其他classe ...

  4. 17.1.1.8?Setting Up Replication with Existing Data设置复制使用存在的数据

    17.1.1.8?Setting Up Replication with Existing Data设置复制使用存在的数据 当设置复制使用存在的数据,你需要确定如何最好的从master 得到数据到sl ...

  5. 【转】Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍

    Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍 要求: 今天要测试上千条数据,且每条数据要求执行多次,(模拟多用户多次抽奖) 1.用户id有175个,且没有任何排序规 ...

  6. Jmeter===Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍(转)

    Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍 要求: 今天要测试上千条数据,且每条数据要求执行多次,(模拟多用户多次抽奖) 1.用户id有175个,且没有任何排序规 ...

  7. elasticsearch负载均衡节点——客户端节点 node.master: false node.data: false 其他配置和master 数据节点一样

    elasticSearch的配置文件中有2个参数:node.master和node.data.这两个参 数搭配使用时,能够帮助提供服务器性能. 数据节点node.master: false node. ...

  8. iOS教程:如何使用Core Data – 预加载和引入数据

    这是接着上一次<iOS教程:Core Data数据持久性存储基础教程>的后续教程,程序也会使用上一次制作完成的. 再上一个教程中,我们只做了一个数据模型,之后我们使用这个数据模型中的数据创 ...

  9. Azure Data Factory(二)复制数据

    一,引言 上一篇主要只讲了Azure Data Factory的一些主要概念,今天开始新的内容,我们开始通过Azure DevOps 或者 git 管理 Azure Data Factory 中的源代 ...

随机推荐

  1. 关于PHP 时区错误的问题

    php的ini文件中时区配置默认为关闭状态 这会导致调用时间函数时出错,所以要开启时区并且配置自己的时区: 查询手册找到所有的时区有: 所以修改配置为: 重启apache问题解决

  2. 编译安装nrpe,配置监控mysql端口和主从状态

    1.安装插件 # tar xvf nagios-plugins-1.4.13.tar.gz # cd nagios-plugins-1.4.13 # ./configure # make && ...

  3. 如何让自己的广播只让指定的 app 接收?

    1.自己的应用(假设名称为应用 A)在发送广播的时候给自己发送的广播添加自定义权限,假设权限名为:com.itheima.android.permission , 然后需要在应用 A 的 Androi ...

  4. Codeforces 914F. Substrings in a String(bitset)

    比赛的时候怎么没看这题啊...血亏T T 对每种字符建一个bitset,修改直接改就好了,查询一个区间的时候对查询字符串的每种字符错位and一下,然后用biset的count就可以得到答案了... # ...

  5. bzoj5210最大连通子块和

    题解: 考虑朴素的dp:$$f_{u} = max(\sum_{v} f_{v} + w_{u} , 0)  \ \ \ \ h_{u} = max( max_{v} \{ h_{v} \}  , h ...

  6. poi导出word表格详解 超详细了

    转:非常感谢原作者 poi导出word表格详解 2018年07月20日 10:41:33 Z丶royAl 阅读数:36138   一.效果如下 二.js代码 function export_word( ...

  7. [python]python安装包错误

    “UnicodeDecodeError: ‘ascii’ codec can’t decode : ordinal not )” 在windows XP上 解决方法: Solution: ====== ...

  8. Redis 3.2.8集群+Sentinel部署

    Redis3.2.8集群搭建 采用官方推荐的三主三从分片方案,本例中所有节点部署在一台主机上. 软件安装: tar zxvf redis-3.2.8.tar.gz cd  redis-3.2.8 ma ...

  9. Python入门 语法

    Python入门 语法 语言介绍 对象,类型,值 编码规范  https://www.python.org/dev/peps/pep-0008/ 一.语言介绍 编程语言: 机器语言,汇编语言,高级语言 ...

  10. JSP中九大内置对象+request对象的属性介绍和如何应用

    JSP的九大内置对象requestresponseApplicationconfigoutpagepageContextsessionException默认没有,需要进行在Page指令下进行isErr ...