Skip to content

Commit 7b31ec6

Browse files
committed
add
1 parent 7ae64b5 commit 7b31ec6

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

happens_before/test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package main
2+
3+
import (
4+
"sync"
5+
"time"
6+
)
7+
8+
//这里把buffered channel作为semaphore来使用,表面上看最多允许一个goroutine对count进行++和--
9+
//根据Go语言的内存模型,对count变量的访问并没有形成临界区。
10+
func main() {
11+
var wg sync.WaitGroup
12+
var count int
13+
var ch = make(chan bool, 1)
14+
for i := 0; i < 10; i++ {
15+
wg.Add(1)
16+
go func() {
17+
ch <- true
18+
count++
19+
time.Sleep(time.Millisecond)
20+
count--
21+
<-ch
22+
wg.Done()
23+
}()
24+
}
25+
wg.Wait()
26+
}

0 commit comments

Comments
 (0)