HelloKoding

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

goroutines.go

package main

import (
	"fmt"
	"time"
)

func f(s string) {
	fmt.Println(s)
}

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

	go f("i'm async!")

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

	time.Sleep(time.Second)
	fmt.Println("done!")
}

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

Follow HelloKoding