28 Data Race Detector 数据种类探测器:数据种类探测器手册
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:
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)
}
}
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:
$ 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
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:
WARNING: DATA RACE
Read by goroutine 185:
net.(*pollServer).AddFD()
src/net/fd_unix.go:89 +0x398
net.(*pollServer).WaitWrite()
src/net/fd_unix.go:247 +0x45
net.(*netFD).Write()
src/net/fd_unix.go:540 +0x4d4
net.(*conn).Write()
src/net/net.go:129 +0x101
net.func·060()
src/net/timeout_test.go:603 +0xaf Previous write by goroutine 184:
net.setWriteDeadline()
src/net/sockopt_posix.go:135 +0xdf
net.setDeadline()
src/net/sockopt_posix.go:144 +0x9c
net.(*conn).SetDeadline()
src/net/net.go:161 +0xe3
net.func·061()
src/net/timeout_test.go:616 +0x3ed Goroutine 185 (running) created at:
net.func·061()
src/net/timeout_test.go:609 +0x288 Goroutine 184 (running) created at:
net.TestProlongTimeout()
src/net/timeout_test.go:618 +0x298
testing.tRunner()
src/testing/testing.go:301 +0xe8
Options
The GORACE environment variable sets race detector options. The format is:
GORACE="option1=val1 option2=val2"
The options are:
log_path(defaultstderr): The race detector writes its report to a file namedlog_path.pid. The special namesstdoutandstderrcause reports to be written to standard output and standard error, respectively.exitcode(default66): 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(default1): The per-goroutine memory access history is32K * 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(default0): Controls whether the program exits after reporting first data race.
Example:
$ 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:
// +build !race package foo // The test contains a data race. See issue 123.
func TestFoo(t *testing.T) {
// ...
} // The test fails under the race detector due to timeouts.
func TestBar(t *testing.T) {
// ...
} // The test takes too long under the race detector.
func TestBaz(t *testing.T) {
// ...
}
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
func main() {
var wg sync.WaitGroup
wg.Add(5)
for i := 0; i < 5; i++ {
go func() {
fmt.Println(i) // Not the 'i' you are looking for.
wg.Done()
}()
}
wg.Wait()
}
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:
func main() {
var wg sync.WaitGroup
wg.Add(5)
for i := 0; i < 5; i++ {
go func(j int) {
fmt.Println(j) // Good. Read local copy of the loop counter.
wg.Done()
}(i)
}
wg.Wait()
}
Accidentally shared variable
// ParallelWrite writes data to file1 and file2, returns the errors.
func ParallelWrite(data []byte) chan error {
res := make(chan error, 2)
f1, err := os.Create("file1")
if err != nil {
res <- err
} else {
go func() {
// This err is shared with the main goroutine,
// so the write races with the write below.
_, err = f1.Write(data)
res <- err
f1.Close()
}()
}
f2, err := os.Create("file2") // The second conflicting write to err.
if err != nil {
res <- err
} else {
go func() {
_, err = f2.Write(data)
res <- err
f2.Close()
}()
}
return res
}
The fix is to introduce new variables in the goroutines (note the use of :=):
...
_, err := f1.Write(data)
...
_, err := f2.Write(data)
...
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:
var service map[string]net.Addr
func RegisterService(name string, addr net.Addr) {
service[name] = addr
}
func LookupService(name string) net.Addr {
return service[name]
}
To make the code safe, protect the accesses with a mutex:
var (
service map[string]net.Addr
serviceMu sync.Mutex
) func RegisterService(name string, addr net.Addr) {
serviceMu.Lock()
defer serviceMu.Unlock()
service[name] = addr
} func LookupService(name string) net.Addr {
serviceMu.Lock()
defer serviceMu.Unlock()
return service[name]
}
Primitive unprotected variable
Data races can happen on variables of primitive types as well (bool, int, int64, etc.), as in this example:
type Watchdog struct{ last int64 }
func (w *Watchdog) KeepAlive() {
w.last = time.Now().UnixNano() // First conflicting access.
}
func (w *Watchdog) Start() {
go func() {
for {
time.Sleep(time.Second)
// Second conflicting access.
if w.last < time.Now().Add(-10*time.Second).UnixNano() {
fmt.Println("No keepalives for 10 seconds. Dying.")
os.Exit(1)
}
}
}()
}
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.
type Watchdog struct{ last int64 }
func (w *Watchdog) KeepAlive() {
atomic.StoreInt64(&w.last, time.Now().UnixNano())
}
func (w *Watchdog) Start() {
go func() {
for {
time.Sleep(time.Second)
if atomic.LoadInt64(&w.last) < time.Now().Add(-10*time.Second).UnixNano() {
fmt.Println("No keepalives for 10 seconds. Dying.")
os.Exit(1)
}
}
}()
}
Supported Systems
The race detector runs on darwin/amd64, freebsd/amd64, linux/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 数据种类探测器:数据种类探测器手册的更多相关文章
- 使用Spring Data ElasticSearch+Jsoup操作集群数据存储
使用Spring Data ElasticSearch+Jsoup操作集群数据存储 1.使用Jsoup爬取京东商城的商品数据 1)获取商品名称.价格以及商品地址,并封装为一个Product对象,代码截 ...
- Spring Data:企业级Java的现代数据访问技术(影印版)
<Spring Data:企业级Java的现代数据访问技术(影印版)>基本信息原书名:Spring Data:Modern Data Access for Enterprise Java作 ...
- 转:代码的坏味道之二十 :Data Class(纯稚的数据类)或POJO
所谓Data Class是指:它们拥有一些值域(fields),以及用于访问(读写]这些值域的函数,除此之外一无长物.这样的classes只是一种「不会说话的数据容器」,它们几乎一定被其他classe ...
- 17.1.1.8?Setting Up Replication with Existing Data设置复制使用存在的数据
17.1.1.8?Setting Up Replication with Existing Data设置复制使用存在的数据 当设置复制使用存在的数据,你需要确定如何最好的从master 得到数据到sl ...
- 【转】Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍
Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍 要求: 今天要测试上千条数据,且每条数据要求执行多次,(模拟多用户多次抽奖) 1.用户id有175个,且没有任何排序规 ...
- Jmeter===Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍(转)
Jmeter中使用CSV Data Set Config参数化不重复数据执行N遍 要求: 今天要测试上千条数据,且每条数据要求执行多次,(模拟多用户多次抽奖) 1.用户id有175个,且没有任何排序规 ...
- elasticsearch负载均衡节点——客户端节点 node.master: false node.data: false 其他配置和master 数据节点一样
elasticSearch的配置文件中有2个参数:node.master和node.data.这两个参 数搭配使用时,能够帮助提供服务器性能. 数据节点node.master: false node. ...
- iOS教程:如何使用Core Data – 预加载和引入数据
这是接着上一次<iOS教程:Core Data数据持久性存储基础教程>的后续教程,程序也会使用上一次制作完成的. 再上一个教程中,我们只做了一个数据模型,之后我们使用这个数据模型中的数据创 ...
- Azure Data Factory(二)复制数据
一,引言 上一篇主要只讲了Azure Data Factory的一些主要概念,今天开始新的内容,我们开始通过Azure DevOps 或者 git 管理 Azure Data Factory 中的源代 ...
随机推荐
- BZOJ3688 折线统计 【dp + BIT】
题目链接 BZOJ3688 题解 将点排序 设\(f[i][j][0|1]\)表示以第\(i\)点结尾,有\(j\)段,最后一段上升或者下降的方案数 以上升为例 \[f[i][j][0] = \sum ...
- Java之初学异常
异常 学习异常的笔记记录 异常 异常的概念 指的是程序在执行过程中,出现的非正常的情况,最终会导致JVM的非正常停止. 异常指的并不是语法错误,语法错了,编译不通过,不会产生字节码文件,根本不能运行. ...
- 团体程序设计天梯赛 L1-006. 连续因子
Two ways: 1.接近O(n) #include <stdio.h> #include <stdlib.h> #include <math.h> int ma ...
- RF - selenium - 常用关键字
1. 打开浏览器 Open Browser htpp://www.testclass.net chrome 2. 关闭浏览器 Close Browsers Close All Browse ...
- SSO基于cas的登录
概念介绍 1.定义 CAS ( CentralAuthentication Service ) 是 Yale 大学发起的一个企业级的.开源的项目,旨在为 Web 应用系统提供一种可靠的单点登录解决方法 ...
- 利用VisualStudio单元测试框架举一个简单的单元测试例子
本随笔很简单,不涉及mock和stub对象,而是只给出一个简单的利用Visual Studio单元测试框架的最简单例子.如果需要深入理解Unit Test的原理与艺术,请参考<The art o ...
- Docker入门与应用系列(一)介绍和部署
Docker介绍 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制, ...
- Tomcat假死排查方案
使用Tomcat作为Web服务器的时候偶尔会遇到Tomcat停止响应的情况,通过netstat查看端口情况会发现tomcat的端口出现大量的CLOSE_WAIT,此时Tomcat会停止响应前端请求,同 ...
- Kafka 0.8 Controller设计机制和状态变化
在kafka集群中,其中一个broker server作为中央控制器Control,负责管理分区和副本状态并执行管理着这些分区的重新分配. 下面说明如何通过中央控制器操作分区和副本的状态. 名词解释 ...
- windows之tracert命令
tracert命令是使用从本地到目标网站所在网络服务器的一系列网络节点的访问速度, 网络节点最多支持显示30个.命令格式是tracert加空格加目标网站名称(也可以输入目标网站的IP地址). 先以百度 ...