Go is a concurrent language. We must first understand what is concurrency.

Concurrency, do lots of things at once. That’s different from doing lots of things at the same time (parallelism).

Related course: Introducing Go: Build Reliable, Scalable Programs

Concurrency in Go

Parallelism vs concurrency

What’s the difference?

Lets say we have two tasks, in concurrency the single core processor can work on each task for a brief amount of time.

In parallelism, two cores can work on each task respectively.

Parallelism does not constantly result in quicker times, because components might to “communicate” with each other.

Goroutines

Concurrency is part of the go programming language. It uses Goroutines.

Goroutines are functions that run concurrently with other functions. Go can have a large number of goroutines running concurrently.

If you have a function called hello, you can start a Go routine with:

1
go hello()

In a program that may look like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"fmt"
)

func hello() {
fmt.Println("Hello world")
}

func main() {
go hello()
fmt.Println("main")
}

When you run this program with go run example.go, you’ll see it only outputs “main”. That’s because Go goes to the next line directly. Go terminates, so the Go routine didn’t have to run.

The main function is running in its own Goroutine.

That can be solved by adding the sleep function,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
"fmt"
"time"
)

func hello() {
fmt.Println("Hello world")
}

func main() {
go hello()
time.Sleep( 1 * time.Second)
fmt.Println("main")
}

Running concurrently

Go routines run concurrently. If you create some functions, you can see they are exeuted in a concurrent way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
"fmt"
"time"
)

func number() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d ", i)
time.Sleep(200 * time.Millisecond)
}
}

func letter() {
for i := 0; i < 10; i++ {
fmt.Printf("%c ", ('a'+i) )
time.Sleep(200 * time.Millisecond)
}
}

func main() {
go number()
go letter()
time.Sleep( 1 * time.Second)
fmt.Println("main")
}


This outputs “1 a b 2 3 c d 4 5 e main”. The lines below execute the methods concurrently:

1
2
go number()
go letter()