ecs事件去除协程id

This commit is contained in:
xzb 2023-09-15 11:17:31 +08:00
parent c3b9d965c6
commit 747a81e44a
2 changed files with 10 additions and 54 deletions

View File

@ -45,43 +45,19 @@ func processAllEvents(w World) {
events.ProcessAllEvents(w.(*world).world)
}
// 订阅该类型的事件
func (me *EventType[T]) Subscribe(wd World, subscriber Subscriber[T]) {
if wd.GoroutineId() == currentGoId() {
me.subscribe(wd, subscriber)
} else {
wd.(*world).chanManageEvent <- func() {
me.subscribe(wd, subscriber)
}
}
}
// 取消订阅该类型的事件
func (me *EventType[T]) Unsubscribe(wd World, subscriber Subscriber[T]) {
if wd.GoroutineId() == currentGoId() {
me.unsubscribe(wd, subscriber)
} else {
wd.(*world).chanManageEvent <- func() {
me.unsubscribe(wd, subscriber)
}
}
}
// 发布该类型的事件
func (me *EventType[T]) Publish(wd World, event *T) {
if wd.GoroutineId() == currentGoId() {
me.publish(wd, event)
} else {
// 在world协程外执行
func (me *EventType[T]) PublishOutWorld(wd World, event *T) {
wd.(*world).chanManageEvent <- func() {
me.publish(wd, event)
}
me.Publish(wd, event)
}
}
///////////////////////////////////////////////////////////////////////////////////
// 订阅该类型的事件
func (me *EventType[T]) subscribe(wd World, subscriber Subscriber[T]) {
// 在world启动前执行
func (me *EventType[T]) Subscribe(wd World, subscriber Subscriber[T]) {
me.subscriberMapLock.Lock()
defer me.subscriberMapLock.Unlock()
//
@ -97,7 +73,8 @@ func (me *EventType[T]) subscribe(wd World, subscriber Subscriber[T]) {
}
// 取消订阅该类型的事件
func (me *EventType[T]) unsubscribe(wd World, subscriber Subscriber[T]) {
// 在world启动前执行
func (me *EventType[T]) Unsubscribe(wd World, subscriber Subscriber[T]) {
me.subscriberMapLock.Lock()
defer me.subscriberMapLock.Unlock()
//
@ -109,7 +86,8 @@ func (me *EventType[T]) unsubscribe(wd World, subscriber Subscriber[T]) {
}
// 发布该类型的事件
func (me *EventType[T]) publish(wd World, event *T) {
// 在world协程中执行
func (me *EventType[T]) Publish(wd World, event *T) {
me.et.Publish(wd.(*world).world, *event)
}

View File

@ -1,11 +1,8 @@
package ecs
import (
"bytes"
"fmt"
"log"
"runtime"
"strconv"
"time"
"github.com/yohamta/donburi"
@ -49,11 +46,9 @@ type World interface {
Close()
Tick() int
Running() bool
GoroutineId() uint64
}
type world struct {
gId uint64
world donburi.World
systems []ISystem
state WorldState
@ -80,9 +75,6 @@ func NewWorld(tick int) World {
chanManageEvent: make(chan ManageEventFunc, 1024),
}
}
func (w *world) GoroutineId() uint64 {
return w.gId
}
func (w *world) Running() bool {
return w.state == Running
}
@ -196,7 +188,6 @@ func (w *world) processManageEventFuncs() {
}
func (w *world) run() {
w.gId = currentGoId()
for {
select {
case <-w.quit: // 退出信号
@ -238,16 +229,3 @@ func (w *world) run() {
}
}
}
// 获取当前协程id
func currentGoId() (gid uint64) {
b := make([]byte, 16)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, err := strconv.ParseUint(string(b), 10, 64)
if err != nil {
panic(err)
}
return n
}