golang互斥锁的两种实现

1.用Mutex实现

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. var num int
  7. var mtx sync.Mutex
  8. var wg sync.WaitGroup
  9. func add() {
  10. mtx.Lock()
  11. defer mtx.Unlock()
  12. defer wg.Done()
  13. num += 1
  14. }
  15. func main() {
  16. for i := 0; i < 100; i++ {
  17. wg.Add(1)
  18. go add()
  19. }
  20. wg.Wait()
  21. fmt.Println("num:", num)
  22. }

2.使用chan实现

  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. var num int
  7. func add(h chan int, wg *sync.WaitGroup) {
  8. defer wg.Done()
  9. h <- 1
  10. num += 1
  11. <-h
  12. }
  13. func main() {
  14. ch := make(chan int, 1)
  15. wg := &sync.WaitGroup{}
  16. for i := 0; i < 100; i++ {
  17. wg.Add(1)
  18. go add(ch, wg)
  19. }
  20. wg.Wait()
  21. fmt.Println("num:", num)
  22. }