package main
import (
"fmt"
"sync"
)
// 共享的计数器
var counter int
// 通过指针调用的函数
func incrementCounter(wg *sync.WaitGroup, m *sync.Mutex) {
defer wg.Done()
m.Lock()
defer m.Unlock()
counter++
fmt.Printf("Counter incremented to %d\n", counter)
}
func main() {
var wg sync.WaitGroup
var m sync.Mutex
// 启动多个goroutine调用incrementCounter函数
for i := 0; i < 10; i++ {
wg.Add(1)
go incrementCounter(&wg, &m)
}
wg.Wait()
fmt.Println("All goroutines completed.")
}
每天编码的小黑子
2024-05-25 06:28:35