Ai
1 Star 0 Fork 0

码农兴哥/go-demo-2025

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main6.go 2.49 KB
一键复制 编辑 原始数据 按行查看 历史
renxing 提交于 2025-12-19 16:10 +08:00 . Go语言条件变量sync.Cond用法示例
package main
import (
"fmt"
"sync"
"time"
)
func broadcastExample() {
fmt.Println("=== Broadcast广播机制示例 ===")
var mu sync.Mutex
cond := sync.NewCond(&mu)
var counter int
target := 5
// 启动多个等待者
for i := 0; i < 5; i++ {
go func(id int) {
mu.Lock()
defer mu.Unlock()
fmt.Printf("等待者 %d: 开始等待\n", id)
// 等待条件:counter >= target
for counter < target {
cond.Wait()
fmt.Printf("等待者 %d: 被唤醒,检查条件 counter=%d\n",
id, counter)
}
fmt.Printf("等待者 %d: 条件满足,继续执行\n", id)
}(i)
}
// 给等待者一些时间进入等待状态
time.Sleep(100 * time.Millisecond)
// 逐步增加counter
go func() {
for i := 0; i <= target; i++ {
time.Sleep(500 * time.Millisecond)
mu.Lock()
counter = i
fmt.Printf("设置者: 设置 counter=%d\n", counter)
mu.Unlock()
if i == target {
// 当条件满足时,广播通知所有等待者
fmt.Println("设置者: 条件满足,广播通知所有等待者")
cond.Broadcast()
} else {
// 条件未满足,只通知一个等待者(通常用于测试)
cond.Signal()
}
}
}()
time.Sleep(5 * time.Second)
}
// Broadcast与Signal的区别示例
func broadcastVsSignal() {
fmt.Println("\n=== Broadcast vs Signal 区别 ===")
var mu sync.Mutex
cond := sync.NewCond(&mu)
var resourceAvailable bool
fmt.Println("场景1: 使用Signal(只唤醒一个)")
for i := 0; i < 3; i++ {
go func(id int) {
mu.Lock()
defer mu.Unlock()
for !resourceAvailable {
fmt.Printf("Goroutine %d: 等待资源\n", id)
cond.Wait()
}
fmt.Printf("Goroutine %d: 获取资源\n", id)
}(i)
}
time.Sleep(100 * time.Millisecond)
// 使用Signal只唤醒一个
mu.Lock()
resourceAvailable = true
fmt.Println("设置资源可用(Signal)")
mu.Unlock()
cond.Signal()
time.Sleep(1 * time.Second)
fmt.Println("\n场景2: 使用Broadcast(唤醒所有)")
resourceAvailable = false
for i := 3; i < 6; i++ {
go func(id int) {
mu.Lock()
defer mu.Unlock()
for !resourceAvailable {
fmt.Printf("Goroutine %d: 等待资源\n", id)
cond.Wait()
}
fmt.Printf("Goroutine %d: 获取资源\n", id)
}(i)
}
time.Sleep(100 * time.Millisecond)
// 使用Broadcast唤醒所有
mu.Lock()
resourceAvailable = true
fmt.Println("设置资源可用(Broadcast)")
mu.Unlock()
cond.Broadcast()
time.Sleep(1 * time.Second)
}
func main() {
broadcastExample()
broadcastVsSignal()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/rxbook/go-demo-2025.git
git@gitee.com:rxbook/go-demo-2025.git
rxbook
go-demo-2025
go-demo-2025
master

搜索帮助