Documentation
¶
Overview ¶
Package wait 提供基于 ID 的等待/通知机制。
主要功能:
- 注册等待某个 ID 的事件
- 触发某个 ID 的所有等待者
- 检查 ID 是否已注册
- 使用分片锁避免锁竞争(64 个分片)
使用场景:
- 异步任务完成通知
- 请求-响应模式
- 事件驱动架构
- 分布式协调
基本用法:
import "github.com/L8CHAT/l8chat-util/wait"
// 创建 Wait 实例 w := wait.New()
// 协程 1: 注册等待
go func() {
ch := w.Register(123) // 注册等待 ID 123
data := <-ch // 阻塞等待
fmt.Println("收到数据:", data)
}()
// 协程 2: 触发通知 time.Sleep(time.Second) w.Trigger(123, "hello") // 触发 ID 123 的等待者
并发用法:
w := wait.New()
// 多个协程等待不同的 ID
for i := 0; i < 100; i++ {
id := uint64(i)
go func() {
ch := w.Register(id)
result := <-ch
// 处理结果...
}()
}
// 触发所有等待者
for i := 0; i < 100; i++ {
w.Trigger(uint64(i), fmt.Sprintf("result-%d", i))
}
技术特点:
- 使用分片锁(64 个分片)避免锁竞争
- 基于 channel 的通知机制
- 自动清理已触发的等待者
- 线程安全
注意事项:
- 每个 ID 只能注册一次,重复注册会 panic
- Trigger 后 channel 会自动关闭
- 如果 ID 未注册,Trigger 不会有任何效果
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Wait ¶
type Wait interface {
// Register waits returns a chan that waits on the given ID.
// The chan will be triggered when Trigger is called with
// the same ID.
Register(id uint64) <-chan interface{}
// Trigger triggers the waiting chans with the given ID.
Trigger(id uint64, x interface{})
IsRegistered(id uint64) bool
}
Wait Wait
Click to show internal directories.
Click to hide internal directories.