Practical coding guides

goroutine in Golang

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)

Lets take a look at the following example


package main

import (

func f(s string) {

func main() {
	f("i'm sync!")

	go f("i'm async!")

	go func(s string) {
	}("i'm async too!")



i'm sync!
i'm async!
i'm async too!

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) {
}("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 message between goroutines. Channels are block and synchronization by default to gurantee two goroutines in a known state

Follow HelloKoding