小结:

1、

  1. conflicting access

2、性能危害 优化

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.

3、典型案例与修复

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. ...

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 the sync/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. }

Unsynchronized send and close operations

As this example demonstrates, unsynchronized send and close operations on the same channel can also be a race condition:

  1. c := make(chan struct{}) // or buffered channel
  2.  
  3. // The race detector cannot derive the happens before relation
  4. // for the following send and close operations. These two operations
  5. // are unsynchronized and happen concurrently.
  6. go func() { c <- struct{}{} }()
  7. close(c)

According to the Go memory model, a send on a channel happens before the corresponding receive from that channel completes. To synchronize send and close operations, use a receive operation that guarantees the send is done before the close:

  1. c := make(chan struct{}) // or buffered channel
  2.  
  3. go func() { c <- struct{}{} }()
  4. <-c
  5. close(c)

4、

数据竞争产生场景:
1、循环计数
Race on loop counter
2、意外地共享变量
Accidentally shared variable
3、没有被保护的全局变量
Unprotected global variable
4、没有被保护的基本类型
Primitive unprotected variable
5、没有同步地在同样的chan上收发操作
Unsynchronized send and close operations

How to detect data races · YourBasic Go https://yourbasic.org/golang/detect-data-races/

Data races can happen easily and are hard to debug. Luckily, the Go runtime is often able to help.

Use -race to enable the built-in data race detector.

  1. $ go test -race [packages]
  2. $ go run -race [packages]

Example

Here’s a program with a data race:

  1. package main
  2. import "fmt"
  3. func main() {
  4. i := 0
  5. go func() {
  6. i++ // write
  7. }()
  8. fmt.Println(i) // concurrent read
  9. }

Running this program with the -race options tells us that there’s a race between the write at line 7 and the read at line 9:

  1. $ go run -race main.go
  2. 0
  3. ==================
  4. WARNING: DATA RACE
  5. Write by goroutine 6:
  6. main.main.func1()
  7. /tmp/main.go:7 +0x44
  8. Previous read by main goroutine:
  9. main.main()
  10. /tmp/main.go:9 +0x7e
  11. Goroutine 6 (running) created at:
  12. main.main()
  13. /tmp/main.go:8 +0x70
  14. ==================
  15. Found 1 data race(s)
  16. exit status 66

Details

The data race detector does not perform any static analysis. It checks the memory access in runtime and only for the code paths that are actually executed.

It runs on darwin/amd64, freebsd/amd64, linux/amd64 and windows/amd64.

The overhead varies, but typically there’s a 5-10x increase in memory usage, and 2-20x increase in execution time.

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.
  • atexit_sleep_ms (default 1000): Amount of milliseconds to sleep in the main goroutine before exiting.

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 the sync/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. }

Unsynchronized send and close operations

As this example demonstrates, unsynchronized send and close operations on the same channel can also be a race condition:

  1. c := make(chan struct{}) // or buffered channel
  2.  
  3. // The race detector cannot derive the happens before relation
  4. // for the following send and close operations. These two operations
  5. // are unsynchronized and happen concurrently.
  6. go func() { c <- struct{}{} }()
  7. close(c)

According to the Go memory model, a send on a channel happens before the corresponding receive from that channel completes. To synchronize send and close operations, use a receive operation that guarantees the send is done before the close:

  1. c := make(chan struct{}) // or buffered channel
  2.  
  3. go func() { c <- struct{}{} }()
  4. <-c
  5. close(c)

Supported Systems

The race detector runs on linux/amd64linux/ppc64lelinux/arm64freebsd/amd64netbsd/amd64darwin/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.

The race detector currently allocates an extra 8 bytes per defer and recover statement. Those extra allocations are not recovered until the goroutine exits. This means that if you have a long-running goroutine that is periodically issuing defer and recover calls, the program memory usage may grow without bound. These memory allocations will not show up in the output of runtime.ReadMemStats or runtime/pprof.

detect data races 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.的更多相关文章

  1. Could not load file or assembly 'System.Data.SQLite' or one of its dependencies. An attempt was made to load a program

    今天同事在一个服务器(winserver 2008 x64)上新建了一个IIS(7) 网站,但是报了如下错误: Could not load file or assembly 'System.Data ...

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

    Data Race Detector 数据种类探测器:数据种类探测器手册 Introduction Usage Report Format Options Excluding Tests How To ...

  3. A record--Offline deployment of Big Data Platform CDH Cluster

    A record--Offline deployment of Big Data Platform CDH Cluster Tags: Cloudera-Manager CDH Hadoop Depl ...

  4. 朝花夕拾之--大数据平台CDH集群离线搭建

    body { border: 1px solid #ddd; outline: 1300px solid #fff; margin: 16px auto; } body .markdown-body ...

  5. 解压版MySQL安装说明

    一.复制my.ini到MySQL解压的目录 例如:E:\MySQL 二.修改my.ini第39~40行 basedir = "E:\\MySQL" datadir = " ...

  6. AIX日常维护

    1  /etc/security/limits与limit命令 AIX 5.3上 下面是文件/etc/security/limits文件里面有关软限制和硬限制的部分. * * Sizes are in ...

  7. MySQL 5.5.35 单机多实例配置详解

    一.前言 二.概述 三.环境准备 四.安装MySQL 5.5.35 五.新建支持多实例的配置文件(我这里配置的是四个实例) 六.初始化多实例数据库 七.提供管理脚本 mysqld_multi.serv ...

  8. 【MySQL for Mac】终极解决——MySQL在Mac的字符集设置

    这个问题烦恼一天了,现在终于得以解决.分享给大家 首先贴出来,亲测不可行的博客连接: http://www.2cto.com/database/201305/215563.html http://bl ...

  9. (转载)绿色版Mysql的安装配置

    本文出自于:http://johnnyhg.javaeye.com/blog/245544 一.下载MySQL http://www.mysql.org/downloads 我下载的是mysql-no ...

随机推荐

  1. IQueryable的简单封装

    IQueryable的简单封装 前言 前两天在园子上看到一个问题 半年前我也考虑过这些问题,但由于这样那样的问题,没有尝试去解决. 后来公司用上了 abp vnext ,然后有一部分代码可以这样写 p ...

  2. React Hook 入门使用

    React Hook 是什么 1.没有比官网说的更好的 HOOK 1. React Hook 官方 2. 用我们自己的话说,它是一个钩子函数,用来处理组件间的状态的一个方法,暂时理解为一个高阶函数吧. ...

  3. 本地TOMCAT启动打包项目(WAR)

    首先打个包,右击项目-->Export...   选择WEB-->WAR file-->Next   选个放置地址,勾选红框处-->finish   找到自己的tomcat目录 ...

  4. 简单谈谈网络抓包,特别是thrift 接口

    按照惯例先谈谈最近情况,最近不是刚好跨年吗?看到很多人都在写年度总结,所以我也在写年度总结文章(其实之前我基本没有写过的,今年有点感触,也想记录一下),结果发现写起来有点多,之前还想着元旦前发出来,结 ...

  5. Java图片的灰度处理方法

    通过看网上各种大牛的总结,和自己亲身测试总结一下Java图片的灰度处理方法 (1)我们熟知的图片中的像素点有RGB值. (2)图片灰度化的方式大概分为四种,第一种是最大值法(取颜色RGB中的最大值作为 ...

  6. Redis学习之路(四)Redis-cluster java api操作

    import redis.clients.jedis.HostAndPort;import redis.clients.jedis.JedisCluster;import java.util.Hash ...

  7. Prometheus集群介绍-1

    Prometheus监控介绍 公司做教育的,要迁移上云,所以需要我这边从零开始调研加后期维护Prometheus:近期看过二本方面的prometheus书籍,一本是深入浅出一般是实战方向的:官方文档主 ...

  8. 基于nginx实现web服务器的双机热备

    1.适用场景 对于部署重要的服务,会使用两台服务器,互相备份,共同执行同一服务.当一台服务器出现故障时,可以由另一台服务器承担服务任务,从而在不需要人工干预的情况下,自动保证系统能持续提供服务.双机热 ...

  9. Java 设置Excel条件格式(高亮条件值、应用单元格值/公式/数据条等类型)

    概述 在Excel中,应用条件格式功能可以在很大程度上改进表格的设计和可读性,用户可以指定单个或者多个单元格区域应用一种或者多种条件格式.本篇文章,将通过Java程序示例介绍条件格式的设置方法,设置条 ...

  10. XSS-labs通关挑战(xss challenge)

    XSS-labs通关挑战(xss challenge) 0x00 xss-labs   最近在看xss,今天也就来做一下xss-labs通过挑战.找了好久的源码,终于被我给找到了,因为在GitHub上 ...