In this article, you will learn about concurrency programming in Golang with goroutine
In Golang, goroutine is a light-weight thread managed by Go runtime. You can use goroutines to run functions asynchronously with this syntax
go func(x, y, z)
Let's take a look at the following example
Output
i'm sync!
i'm async!
i'm async too!
done!
f("i'm sync!")
is run synchronously on the main thread/goroutine
go f("i'm async!")
is run asynchronously on the another goroutine
Apart from using goroutine with a defined function, you can also use it with an anonymous function
go func(s string) {
fmt.Println(s)
}("i'm async too!")
The above function is also run asynchronously on the another goroutine
Awaiting a collection of goroutines to finish
In the previous example, time.Sleep(time.Second)
try to wait a second for all goroutines to finish before the program exited. In practice, you can use sync.WaitGroup as it's a better way to handle the case
Exchange messages between goroutines
You can use channels to send and receive messages between goroutines. Channels are block and synchronization by default to guarantee two goroutines in a known state