File tree Expand file tree Collapse file tree 3 files changed +87
-0
lines changed Expand file tree Collapse file tree 3 files changed +87
-0
lines changed Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ "time"
6
+ )
7
+
8
+ // 生产者:生成 factor 整数倍的序列
9
+ func producer (factor int , out chan <- int ) {
10
+ for i := 0 ; ; i ++ {
11
+ out <- i * factor
12
+ }
13
+ }
14
+
15
+ // 消费者
16
+ func consumer (in <- chan int ) {
17
+ for v := range in {
18
+ fmt .Println (v )
19
+ }
20
+ }
21
+
22
+ func main () {
23
+ ch := make (chan int , 64 )
24
+
25
+ go producer (3 , ch )
26
+ // go producer(5, ch)
27
+ go producer (7 , ch )
28
+ go consumer (ch )
29
+
30
+ time .Sleep (500 * time .Millisecond )
31
+
32
+ // // Ctrl+C 退出
33
+ // sig := make(chan os.Signal, 1)
34
+ // signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
35
+ // fmt.Printf("quit (%v)\n", <-sig)
36
+ }
Original file line number Diff line number Diff line change
1
+ package singleton
2
+
3
+ import (
4
+ "sync"
5
+ "sync/atomic"
6
+ )
7
+
8
+ type singleton struct {}
9
+
10
+ var (
11
+ instance * singleton
12
+ initialized uint32
13
+ mu sync.Mutex
14
+ )
15
+
16
+ // 原子操作`atomic`配合互斥锁`mutex`可以实现非常高效的单件模式
17
+ // 增加一个原子标记位`atomic.StoreUint32(addr *uint32, val uint32)`,
18
+ // 通过原子检测标记位状态`atomic.LoadUint32(addr *unit32)`
19
+ func Instance () * singleton {
20
+ if atomic .LoadUint32 (& initialized ) == 1 {
21
+ return instance
22
+ }
23
+
24
+ mu .Lock ()
25
+ defer mu .Unlock ()
26
+
27
+ if instance == nil {
28
+ defer atomic .StoreUint32 (& initialized , 1 )
29
+ instance = & singleton {}
30
+ }
31
+
32
+ return instance
33
+ }
Original file line number Diff line number Diff line change
1
+ package singleton
2
+
3
+ import (
4
+ "sync"
5
+ )
6
+
7
+ var (
8
+ // singleton *singleton
9
+ once sync.Once
10
+ )
11
+
12
+ func Instance2 () * singleton {
13
+ once .Do (func () {
14
+ instance = & singleton {}
15
+ })
16
+
17
+ return instance
18
+ }
You can’t perform that action at this time.
0 commit comments