Codementor Events

Golang: The Event Emitter

Published Jul 27, 2018
Golang: The Event Emitter

Event Emitter is a very common term of node js, javascript, but how do we achieve this in Golang? I’ll gonna tell you about a very interesting thing in communicate between goroutines in Golang

First approach, the easiest approach is use a infinite loop to listen for an event:

for{condition goes here...}

But, when you do a for statement, it’ll consume most of current CPU cycle, which impacts very much in performance

Second approach, the more better approach than first approach is sleep for 1 millisecond before checking condition again:

for {
    condition goes here...
    time.Sleep(time.Millisecond)
}

But, it still consume cpu which made me come up with a new approach of Golang to notify the goroutine (the event) waiting for some condition to complete before running instead of pooling the condition

Third approach, I’ll use sync.Cond which will emit the event for a waiting goroutine, a very simple example is like this:

When sync.Cond is waiting the goroutine is suspend until it receive signal from goroutine outside

You can use channel to achieve this but the very important point of sync.Cond is broadcast event function, which can be used for emit many times, when using channel you can close it to broadcast signal but when channel is closed, you can’t close it again for many times, that why sync.Cond is a natural way to do event emitter in Golang

I implemented a library for event usage, which wraps this idea into very easy usage library

Discover and read more posts from Hau Ma Van
get started
post commentsBe the first to share your opinion
Show more replies