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() {
.Println("Hello world")
fmt}
func main() {
go hello()
.Println("main")
fmt}
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() {
.Println("Hello world")
fmt}
func main() {
go hello()
.Sleep( 1 * time.Second)
time.Println("main")
fmt}
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++ {
.Printf("%d ", i)
fmt.Sleep(200 * time.Millisecond)
time}
}
func letter() {
for i := 0; i < 10; i++ {
.Printf("%c ", ('a'+i) )
fmt.Sleep(200 * time.Millisecond)
time}
}
func main() {
go number()
go letter()
.Sleep( 1 * time.Second)
time.Println("main")
fmt}
This outputs “1 a b 2 3 c d 4 5 e main”. The lines below execute the methods concurrently:
go number()
go letter()