Golang Goroutines is an interesting take on the programming paradigm as it provides the most basic way to get started with concurrency. Just adding go
in front of the function would make it run in a different thread ๐คฏ. Let's jump right to the example.
func main() {
go func() {
fmt.Println("Running in different thread")
}()
fmt.Println("Running in main thread")
}
What do you think if we execute the code... Output: Running in the main thread
is weird isn't it? The reason behind the main thread gets executed and doesn't wait from the concurrent routine to be completed. There are many ways to solve this, most easiest would be using the channel.
Channel
Do you know the ethernet cable, how there are two ends -- one producing signal and the other end receiving it. Channels are based on the same logic. In go
channel can be of two types buffered
or unbuffered
. As the name suggests buffered one holds additional size, while unbuffer doesn't. In this post, we will only focus on the unbuffered one because it would solve the above issue we were facing
func main() {
flagch := make(chan bool)
go func() {
fmt.Println("Running in different thread")
flagch <- true
}()
output := <- flagch
fmt.Printf("Running in main thread %+v", output)
}
Now both of the logs would be displayed on the terminal ๐. But what's happening to the line flagch <- true
is adding data to channel (Producer) while output := <- flagch
is receiving data from the channel (Consumer).
Conclusion
Goroutines are a core addon to the go-programming language that one needs to understand. There are other complex and more practical ways of implementing concurrency in go which will be covered in a later post, bye for now ๐.