test(utils): 添加事件驱动模型测试

- 在 sqrt_test.go 中添加了 fastSqr1 测试函数,用于测试事件驱动模型
- 新增了 Event 和 Uint32AsyncEvent 类型用于测试
- 更新了 go.work、go.mod 和
This commit is contained in:
2025-08-05 16:10:18 +08:00
parent bbbec5dff0
commit cd7583ba05
32 changed files with 1789 additions and 0 deletions

View File

@@ -4,6 +4,8 @@ import (
"fmt"
"math"
"testing"
"github.com/badu/bus"
)
func Test_fastSqrt(t *testing.T) {
@@ -89,3 +91,78 @@ 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
topic := bus.NewTopic[*Uint32AsyncEvent]()
for i := 0; i < 4096; i++ {
topic.Sub(func(v *Uint32AsyncEvent) {
print(v.u)
})
}
topic.Pub(&Uint32AsyncEvent{u: 1})
// finishPubWait := make(chan struct{})
// finishSubWait := make(chan struct{})
// start := make(chan struct{})
// go func() {
// <-start
// topic.PubAsync(&Uint32AsyncEvent{u: 1})
// defer close(finishPubWait)
// }()
// 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")
// }
}
// Various event types
const EventA = 0x01
type Uint32AsyncEvent struct {
u uint32
}
// Event type for testing purposes
type Event struct {
Data string
type1 uint32
}
// Type returns the event type
func (ev Event) Type() uint32 {
return ev.type1
}
// newEventA creates a new instance of an event
func newEventA(data string) Event {
return Event{Data: data, type1: EventA}
}
// Various event types
const EventB1 = 0x02
func newEventB(data string) Event {
return Event{Data: data, type1: EventB1}
}