Does this code have a data race?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
// from https://golang.org/issue/42598
type module struct {
v int
}
func foo() {
mods := []*module{
&module{v: 0},
&module{v: 1},
&module{v: 2},
}
type token struct{}
sem := make(chan token, runtime.GOMAXPROCS(0))
for _, m := range mods {
add := func(m *module) {
sem <- token{}
go func() {
*m = module{v: 42} // write
<-sem
}()
}
add(m) // read
}
// Fill semaphore channel to wait for all tasks to finish.
for n := cap(sem); n > 0; n-- {
sem <- token{}
}
}
|
An issue submitted yesterday appears to point out a bug in the current Go memory model. Further reading:
这段代码有 data race 吗?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
// from https://golang.org/issue/42598
type module struct {
v int
}
func foo() {
mods := []*module{
&module{v: 0},
&module{v: 1},
&module{v: 2},
}
type token struct{}
sem := make(chan token, runtime.GOMAXPROCS(0))
for _, m := range mods {
add := func(m *module) {
sem <- token{}
go func() {
*m = module{v: 42} // write
<-sem
}()
}
add(m) // read
}
// Fill semaphore channel to wait for all tasks to finish.
for n := cap(sem); n > 0; n-- {
sem <- token{}
}
}
|
昨天提交的一个 issue 似乎指出了目前 Go 内存模型中的一个错误。进一步阅读: