1
\$\begingroup\$

I wrote a memory bus struct in golang to allow systems to interact with each other without knowing anything about the receiver.

This is for a game engine. I know it's not good to write games in garbage collected languages like golang, but I enjoy writing in golang so whatever. But since golang has a garbage collector and can cause the game to freeze I want to make sure that the message bus is optimized and not the cause of any freezes. (Besides the obvious overhead to using a message bus)

When looking up what causes the gc to struggle I learned that pointers are a major killer bc it requires the gc to go searching for the pointer. I'd like to know if there is a better way of adding receivers and sending messages that don't require pointers to the message bus.

Here is the MessageBus:

type Message string

type MessageBus struct {
    recievers []func(Message)
    messages  chan Message
}

var (
    WaitGroup sync.WaitGroup
)

func (mb *MessageBus) AddReceiver(r func(Message)) {
    mb.recievers = append(mb.recievers, r)
}

func (mb *MessageBus) GetMessageChan() chan Message {
    return mb.messages
}

func (mb *MessageBus) Shutdown() {
    close(mb.messages)
}

func (mb *MessageBus) Start() {
    for msg := range mb.messages {
        fmt.Println(msg)
        for _, f := range mb.recievers {
            WaitGroup.Add(1)
            go f(msg)
        }
        WaitGroup.Wait()
    }
}

func New() MessageBus {
    return MessageBus{[]func(Message){}, make(chan Message, 1000)}
}

Here is an example of a handler:

type Input struct {
    mb chan<- messagebus.Message
}

func New(mb chan<- messagebus.Message) Input {
    r := Input{mb}
    return r
}

func (r Input) HandleMessage(m messagebus.Message) {
    defer messagebus.WaitGroup.Done()

    time.Sleep(time.Second)
    switch m {
    case "HI":
        r.mb <- "A_PRESSED"
    case "BYE":
        r.mb <- "B_PRESSED"
    }
}

func (r Input) Update() {}

Any help to speed up the transfers or prepare for garbage collection would be much appreciated!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.