sync 包提供了基础的同步方法和锁机制.导入方式为 import "sync"
常用类型定义
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
| type Locker interface { Lock() Unlock() }
type Mutex struct { }
type Once struct { }
type Pool struct {
New func() interface{} }
type WaitGroup struct { }
|
常用函数
Mutex 结构体方法
互斥锁与 goroutine 没有关联,允许一个 goroutine 添加锁,另一个 goroutine 释放锁
1 2 3 4 5 6
|
func (m *Mutex) Lock()
func (m *Mutex) Unlock()
|
Once 结构体方法
1 2 3 4
|
func (o *Once) Do(f func())
|
Pool 结构体方法
1 2 3 4 5 6
|
func (p *Pool) Get() interface{}
func (p *Pool) Put(x interface{})
|
WaitGroup 结构体方法
1 2 3 4 5 6 7 8 9 10
|
func (wg *WaitGroup) Add(delta int)
func (wg *WaitGroup) Done()
func (wg *WaitGroup) Wait()
|
示例
Once 使用示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import ( "fmt" "sync" )
func main() { var once sync.Once for i := 0; i < 5; i++ { once.Do(func() { fmt.Printf("在 i=%v 时被调用\n", i) }) } }
|
Pool 使用示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import ( "fmt" "math/rand" "sync" "time" )
func main() { rand.Seed(time.Now().UnixNano()) var p sync.Pool = sync.Pool{ New: func() interface{} { return rand.Intn(100) }, } for i := 0; i < 5; i++ { fmt.Println(p.Get()) } }
|
WaitGroup 使用示例
- 使用
WaitGroup 等待所有 goroutine 执行结束
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import ( "fmt" "sync" )
func main() {
var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func(i int) { defer wg.Done() fmt.Printf("goroutine %v done\n", i) }(i) } wg.Wait() fmt.Println("main goroutine done") }
|