lundi 10 octobre 2022

How to handle 2 event source using 2 separate thread in golang

This is a design-related question. I have a situation where my application receives events from 2 different sources it is registered with and the application should handle events from these 2 sources parallelly. My Application is already handling events from one source using the buffered channel (where events are queued up and processed one after another). Now I am in a situation where the application needs to handle the events from a different source and I cannot use the same channel here because the Application may have to handle events from these 2 sources parallelly. I am thinking of using another buffered channel to handle the events from the second event source. But I am concerned about the same resource being used to process 2 events parallelly. Even though we use channel we need to again apply sync while processing these events.

Could you please suggest me a better way, any patterns I can use, or a design to handle this situation?

This is the code I have now to handle event from one source

for event := range thisObj.channel {

    log.Printf("Found a new event '%s' to process at the state %s", event, thisObj.currentState)

    stateins := thisObj.statesMap[thisObj.currentState]
    // This is separate go routine. Hence acuire the lock before calling a state to process the event.
    thisObj.mu.Lock()
    stateins.ProcessState(event.EventType, event.EventData)
    thisObj.mu.Unlock()

}

Here thisObj.channel is being created at start up and the events are being added in a separate method. Currently this method is reading events from the channel and processing the events.

Aucun commentaire:

Enregistrer un commentaire