| 12345678910111213141516171819202122232425262728293031323334 |
- package main
- import (
- "fmt"
- "sync"
- )
- const (
- goroutines = 10
- addsPerG = 100
- )
- func main() {
- var (
- counter int
- mu sync.Mutex
- wg sync.WaitGroup
- )
- wg.Add(goroutines)
- for i := 0; i < goroutines; i++ {
- go func() {
- defer wg.Done()
- for j := 0; j < addsPerG; j++ {
- mu.Lock() // 进入临界区
- counter++
- mu.Unlock() // 离开临界区
- }
- }()
- }
- wg.Wait()
- fmt.Println("final counter:", counter)
- }
|