test(common): 重构 Test_event 测试函数
- 重写了 Test_event 测试函数,移除了未使用的测试代码 - 新增了基于 Task 结构的事件处理逻辑 - 实现了任务计数和完成状态的更新 - 添加了事件发布和订阅的示例代码
This commit is contained in:
@@ -92,56 +92,50 @@ func BenchmarkFastSqrtInt(b *testing.B) {
|
||||
}
|
||||
}
|
||||
|
||||
func Test_fastSqr1(b *testing.T) {
|
||||
// scenario : we have a large number of subscribers.
|
||||
// we publish an event and while doing that,
|
||||
// we register another one on a different goroutine
|
||||
func Test_event(b *testing.T) {
|
||||
|
||||
topic := bus.NewTopic[*Uint32AsyncEvent]()
|
||||
for i := 0; i < 4096; i++ {
|
||||
topic.Sub(func(v *Uint32AsyncEvent) {
|
||||
print(v.u)
|
||||
tt := make(map[int]*bus.Listener[*Task], 3)
|
||||
topic := bus.NewTopic[*Task]() //直接注册到用户
|
||||
for i := 0; i < 1; i++ {
|
||||
t := topic.Sub(func(v *Task) { //注册里程碑
|
||||
fmt.Println(v.id)
|
||||
if v.cfunc != nil {
|
||||
v.cont = v.cfunc(v.cont) //增加计数
|
||||
}
|
||||
|
||||
if v.cont > 0 { //如果计数达到,标记任务完成
|
||||
v.done = true
|
||||
}
|
||||
fmt.Println("当前任务计数", v.cont, "是否完成", v.done)
|
||||
})
|
||||
tt[i] = t
|
||||
}
|
||||
topic.Pub(&Task{id: 1, cfunc: func(t uint32) uint32 { //满足任务1后推定
|
||||
|
||||
topic.Pub(&Uint32AsyncEvent{u: 1})
|
||||
// finishPubWait := make(chan struct{})
|
||||
// finishSubWait := make(chan struct{})
|
||||
// start := make(chan struct{})
|
||||
fmt.Println("当前任务计数", t)
|
||||
//实现自定义逻辑
|
||||
//增加用户计数
|
||||
//增加服务器总计数
|
||||
return t + 1
|
||||
|
||||
// go func() {
|
||||
// <-start
|
||||
// topic.PubAsync(&Uint32AsyncEvent{u: 1})
|
||||
// defer close(finishPubWait)
|
||||
// }()
|
||||
}})
|
||||
topic.Pub(&Task{id: 2, done: true})
|
||||
for _, v := range tt {
|
||||
|
||||
// newSubCalled := false
|
||||
|
||||
// go func() {
|
||||
// <-start
|
||||
// topic.Sub(func(v *Uint32AsyncEvent) {
|
||||
// newSubCalled = true
|
||||
// })
|
||||
// close(finishSubWait)
|
||||
// }()
|
||||
|
||||
// close(start) // start both goroutines
|
||||
|
||||
// <-finishPubWait // wait for pub to finish
|
||||
|
||||
// <-finishSubWait // wait for sub to finish
|
||||
|
||||
// if newSubCalled {
|
||||
// print("new subscriber called")
|
||||
// }
|
||||
v.Cancel()
|
||||
}
|
||||
topic.Pub(&Task{id: 1}) //发送事件
|
||||
|
||||
}
|
||||
|
||||
// Various event types
|
||||
const EventA = 0x01
|
||||
|
||||
type Uint32AsyncEvent struct {
|
||||
u uint32
|
||||
type Task struct {
|
||||
id uint32
|
||||
cfunc func(uint32) uint32
|
||||
cont uint32
|
||||
done bool
|
||||
}
|
||||
|
||||
// Event type for testing purposes
|
||||
|
||||
Reference in New Issue
Block a user