Files
bulma/mutex_demo.go

31 lines
593 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"sync"
)
var (
sharedCounter int // 共享资源
mu sync.Mutex // 互斥锁
wg sync.WaitGroup
)
// 对共享计数器进行累加
func muIncrement() {
defer wg.Done()
for i := 0; i < 1000; i++ {
mu.Lock() // 加锁:进入临界区
sharedCounter++
mu.Unlock() // 解锁:退出临界区
}
}
func main() {
wg.Add(5) // 启动5个goroutine并发修改
for i := 0; i < 5; i++ {
go muIncrement()
}
wg.Wait() // 等待所有goroutine完成
fmt.Printf("最终计数器值: %d(预期:5000\n", sharedCounter)
}