DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

golang race

原文链接

由于golang中的go是非常方便的,加上函数又非常容易隐藏go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import(
"time"
"fmt"
"math/rand"
)

func main() {
start := time.Now()
var t *time.Timer
t = time.AfterFunc(randomDuration(), func() {
fmt.Println(time.Now().Sub(start))
t.Reset(randomDuration())
})
time.Sleep(5 * time.Second)
}

func randomDuration() time.Duration {
return time.Duration(rand.Int63n(1e9))
}

time.AfterFunc是会另外启动一个goroutine来进行计时和执行func()。 由于func中有对t(Timer)进行操作(t.Reset),而主goroutine也有对t进行操作(t=time.After)。 这个时候,其实有可能会造成两个goroutine对同一个变量进行竞争的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
runtime  go run -race race1.go
a is 3
==================
WARNING: DATA RACE
Write by goroutine 5:
main.func·001()
/Users/yejianfeng/Documents/workspace/go/src/runtime/race1.go:11 +0x3a

Previous write by main goroutine:
main.main()
/Users/yejianfeng/Documents/workspace/go/src/runtime/race1.go:13 +0xe7

Goroutine 5 (running) created at:
main.main()
/Users/yejianfeng/Documents/workspace/go/src/runtime/race1.go:12 +0xd7
==================
Found 1 data race(s)
exit status 66

通过race的参数,检测相关参数的竞争问题