We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 7ae64b5 commit 7b31ec6Copy full SHA for 7b31ec6
happens_before/test.go
@@ -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