WaitGroup 可以视为一个并发-安全计数器

互斥锁和读写锁

我们总是在 defer 语句中调用 Unlock 。这是一个十分常见的习惯用怯,它使用 Mutex 互斥锁来确保即使出现了 panic ,调用也总是发生。如果不这样,可能会导致程序陷入死锁。

Cond

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. func main() {
  8. c := sync.NewCond(&sync.Mutex{})
  9. queue := make([]interface{}, 0, 10)
  10. removeFromQueue := func(delay time.Duration) {
  11. time.Sleep(delay)
  12. c.L.Lock()
  13. queue = queue[1:]
  14. fmt.Println("Removed from queue")
  15. c.L.Unlock()
  16. c.Signal() // 关键
  17. }
  18. for i := 0; i < 10; i++ {
  19. c.L.Lock()
  20. for len(queue) == 2 {
  21. c.Wait() // 关键
  22. }
  23. fmt.Println("Adding to queue")
  24. queue = append(queue, struct{}{})
  25. go removeFromQueue(1 * time.Second)
  26. c.L.Unlock()
  27. }
  28. }

Once

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. var count int
  8. increment := func() {
  9. count++
  10. }
  11. var once sync.Once
  12. var increments sync.WaitGroup
  13. increments.Add(100)
  14. for i := 0; i < 100; i++ {
  15. go func() {
  16. defer increments.Done()
  17. once.Do(increment)
  18. }()
  19. }
  20. increments.Wait()
  21. fmt.Printf("Count is %d\n", count)
  22. }
  23. 输出:
  24. Count is 1
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. var count int
  8. increment := func() { count++ }
  9. decrement := func() { count-- }
  10. var once sync.Once
  11. once.Do(increment)
  12. once.Do(decrement)
  13. fmt.Printf("Count: %d\n", count)
  14. }
  15. 输出:
  16. Count: 1

注意 sync.Once 只计算调用 Do 方法的次数,而不是多少次唯一调用 Do 方法。

  1. package main
  2. import (
  3. "sync"
  4. )
  5. func main() {
  6. var onceA, onceB sync.Once
  7. var initB func()
  8. initA := func() {
  9. onceB.Do(initB)
  10. }
  11. initB = func() {
  12. onceA.Do(initA)
  13. }
  14. onceA.Do(initA)
  15. }
  16. 输出:
  17. fatal error: all goruntines are asleep - deadlock

Pool

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. myPool := &sync.Pool{New: func() interface{} {
  8. fmt.Println("Creating new instance")
  9. return struct{}{}
  10. }}
  11. a := myPool.Get()
  12. fmt.Println("a:", a)
  13. instance := myPool.Get()
  14. fmt.Println("instacne:", instance)
  15. myPool.Put(instance)
  16. c := myPool.Get()
  17. fmt.Println("c:", c)
  18. }
  19. 输出:
  20. Creating new instance
  21. a: {}
  22. Creating new instance
  23. instacne: {}
  24. c: {}

image.png
image.png

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. func main() {
  7. var numCalcsCreated int
  8. calcPool := &sync.Pool{
  9. New: func() interface{} {
  10. numCalcsCreated += 1
  11. mem := make([]byte, 1024)
  12. return &mem
  13. },
  14. }
  15. calcPool.Put(calcPool.New())
  16. calcPool.Put(calcPool.New())
  17. calcPool.Put(calcPool.New())
  18. calcPool.Put(calcPool.New())
  19. const numWorkers = 1024 * 1024
  20. var wg sync.WaitGroup
  21. wg.Add(numCalcsCreated)
  22. for i := 0; i < numCalcsCreated; i++ {
  23. go func() {
  24. defer wg.Done()
  25. mem := calcPool.Get().(*[]byte)
  26. defer calcPool.Put(mem)
  27. }()
  28. }
  29. wg.Wait()
  30. fmt.Printf("%d calculators were created.", numCalcsCreated)
  31. }
  32. 输出:
  33. 4 calculators were created.