1. sync.Mutex 互斥锁
    1. lock 加锁,unlock解锁
  2. sync.RWMutex 读写锁
    1. 不限制并发读,但是会阻塞 读 和写的同时发生
  3. sync.WaitGroup 【读写分离,为了优化性能】
    1. 等待 一组 goroutine 返回
  4. sync.Once
    1. 保证某段代码只能执行一次
  5. sync.Cond
    1. 让一组 goroutine 在满足特定条件时候被唤醒

Mutex示例

Kubernetes 中 的 informer factory

参考博客

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 来源于 k8s.io/client-go/informers/factory.go
// Start initializes all requested informers.
func (f *sharedInformerFactory) Start(stopCh <-chan struct{}) {
	f.lock.Lock()
	defer f.lock.Unlock()

	for informerType, informer := range f.informers {
		// 如果对应类型的 informer 没有运行,则运行它
		if !f.startedInformers[informerType] {
			go informer.Run(stopCh)
			f.startedInformers[informerType] = true
		}
	}
}

rwMutex 示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
	"fmt"
	"sync"
)

type SafeMap struct {
	mp map[string]interface{}
	m  *sync.RWMutex
}

func New() *SafeMap {
	mp := new(SafeMap)
	mp.mp = make(map[string]interface{}, 0)
	mp.m = &sync.RWMutex{}
	return mp
}
func (w *SafeMap) Get(key string) interface{} {
	w.m.RLock()
	defer w.m.RUnlock()
	return w.mp[key]
}
func (mp *SafeMap) Put(key string, value interface{}) {
	mp.m.Lock()
	defer mp.m.Unlock()
	mp.mp[key] = value
}
func main() {
	mp := New()
	mp.Put("key", 1)
	fmt.Println(mp.Get("key"), mp.Get("key2"))
}

Cond 示例

参考博客