Skip to main content

Modelling real world

Before talking about concurrency, let's think about functions and their meaning. Whether they are concurrent or not, it doesn't matter right now. We just need to know that a function represents some work being done in a certain amount of time.

For the purpose of our book, we will model real-world examples. And what better example of work being done in a certain amount of time can we find than the work inside an office? An office is a place where all kinds of work are being done between 9 and 5 by multiple people who are doing their jobs in their offices while they exchange information between themselves.

Who are you

Since we are going to use code to model real life, let's find a place for you. You are a boss of course! Maybe not the owner of the company, but you run the things around here. You're the man, the hombre who's having things under his control and telling everyone what to do, you are the main function:

package main

import (
"fmt"
)

func main() {
fmt.Println("People say I'm the best boss. They go, 'God, we've never worked in a place like this. You're hilarious, and you get the best out of us.")
}

The main function is our first goroutine. If you previously read about Go concurrency, you might have thought that a goroutine is just a function which is started with the go functionName() statement. We call main the current go routine or just the main goroutine.

Your workers

For now, let's introduce our first worker: Pam. You tell Pam to do her job and the job is done in 2 seconds. Pretty neat!

package main

import (
"fmt"
"time"
)

func main() {
start := time.Now()

worker("Pam")

fmt.Printf("\nall work was done in %s seconds", time.Since(start))
}

func worker(name string) {
fmt.Printf("%s: doing my work...\n", name)
time.Sleep(2 * time.Second)
fmt.Printf("%s: done\n", name)
}

See it in playground

The work is simulated by our worker function, which takes a name param and sleeps for 2 seconds then outputs that the work is done.