sync_mutex.go 445 B

12345678910111213141516171819202122232425262728293031323334
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. const (
  7. goroutines = 10
  8. addsPerG = 100
  9. )
  10. func main() {
  11. var (
  12. counter int
  13. mu sync.Mutex
  14. wg sync.WaitGroup
  15. )
  16. wg.Add(goroutines)
  17. for i := 0; i < goroutines; i++ {
  18. go func() {
  19. defer wg.Done()
  20. for j := 0; j < addsPerG; j++ {
  21. mu.Lock() // 进入临界区
  22. counter++
  23. mu.Unlock() // 离开临界区
  24. }
  25. }()
  26. }
  27. wg.Wait()
  28. fmt.Println("final counter:", counter)
  29. }