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).

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:


go hello()

In a program that may look like this


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,


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:


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:


    go number()
    go letter()