Skip to content

Commit 73c2624

Browse files
committed
race condition solved demo
1 parent ed7e503 commit 73c2624

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"sync"
6+
)
7+
8+
// N 是内存里的一个对象
9+
var (
10+
N = 0
11+
mutex sync.Mutex // +
12+
waitgroup sync.WaitGroup
13+
)
14+
15+
func counter(number *int) {
16+
mutex.Lock() // ++
17+
*number++
18+
mutex.Unlock() // +++
19+
waitgroup.Done()
20+
}
21+
22+
func main() {
23+
24+
for i := 0; i < 1000; i++ {
25+
waitgroup.Add(1)
26+
go counter(&N)
27+
}
28+
waitgroup.Wait()
29+
fmt.Println(N)
30+
}

0 commit comments

Comments
 (0)