Skip to content

Commit b35af75

Browse files
committed
Add concurrent & singleton sample
1 parent f00f6e6 commit b35af75

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed

grammar/concurrent/main.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
}

0 commit comments

Comments
 (0)