From 0d2b5163627e72ff1e77906ef3ba08c3dae1b04e Mon Sep 17 00:00:00 2001 From: xzb <223@qq.com> Date: Thu, 31 Aug 2023 17:49:25 +0800 Subject: [PATCH] =?UTF-8?q?ecs=E4=BA=8B=E4=BB=B6=E5=A4=9Aworld=E6=94=AF?= =?UTF-8?q?=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- events.go | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/events.go b/events.go index 2c60a8c..6444b7d 100644 --- a/events.go +++ b/events.go @@ -1,7 +1,9 @@ package ecs import ( + "fmt" "reflect" + "sync" "github.com/yohamta/donburi" "github.com/yohamta/donburi/features/events" @@ -13,8 +15,9 @@ import ( type ( // 事件类型定义 EventType[T any] struct { - et *events.EventType[T] - subscriberMap map[uintptr]events.Subscriber[T] + et *events.EventType[T] + subscriberMap map[string]events.Subscriber[T] + subscriberMapLock sync.Mutex // } // 事件订阅者定义 Subscriber[T any] func(w World, event T) @@ -30,8 +33,9 @@ func init() { // 创建事件类型的实例 func NewEventType[T any]() *EventType[T] { return &EventType[T]{ - et: events.NewEventType[T](), - subscriberMap: make(map[uintptr]events.Subscriber[T]), + et: events.NewEventType[T](), + subscriberMap: make(map[string]events.Subscriber[T]), + subscriberMapLock: sync.Mutex{}, } } @@ -78,19 +82,25 @@ func (me *EventType[T]) Publish(wd World, event *T) { // 订阅该类型的事件 func (me *EventType[T]) subscribe(wd World, subscriber Subscriber[T]) { - wdSubscriberPointer := reflect.ValueOf(subscriber).Pointer() - me.subscriberMap[wdSubscriberPointer] = func(w donburi.World, event T) { + me.subscriberMapLock.Lock() + defer me.subscriberMapLock.Unlock() + // + subscriberKey := subscriberKey[T](wd, subscriber) + me.subscriberMap[subscriberKey] = func(w donburi.World, event T) { subscriber(wd, event) } - me.et.Subscribe(wd.(*world).world, me.subscriberMap[wdSubscriberPointer]) + me.et.Subscribe(wd.(*world).world, me.subscriberMap[subscriberKey]) } // 取消订阅该类型的事件 func (me *EventType[T]) unsubscribe(wd World, subscriber Subscriber[T]) { - wdSubscriberPointer := reflect.ValueOf(subscriber).Pointer() - if sub, ok := me.subscriberMap[wdSubscriberPointer]; ok { + me.subscriberMapLock.Lock() + defer me.subscriberMapLock.Unlock() + // + subscriberKey := subscriberKey[T](wd, subscriber) + if sub, ok := me.subscriberMap[subscriberKey]; ok { me.et.Unsubscribe(wd.(*world).world, sub) - delete(me.subscriberMap, wdSubscriberPointer) + delete(me.subscriberMap, subscriberKey) } } @@ -98,3 +108,9 @@ func (me *EventType[T]) unsubscribe(wd World, subscriber Subscriber[T]) { func (me *EventType[T]) publish(wd World, event *T) { me.et.Publish(wd.(*world).world, *event) } + +func subscriberKey[T any](wd World, subscriber Subscriber[T]) string { + wdSubscriberPointer := reflect.ValueOf(subscriber).Pointer() + subscriberKey := fmt.Sprintf("%d-%d", wd.GoroutineId(), wdSubscriberPointer) + return subscriberKey +}