EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Go Programming Language

Concurrency in Golang

Goroutines allow functions to run concurrently and consume significantly less memory compared to traditional threads. Every Go program begins execution with a primary Goroutine, commonly referred to as the main Goroutine. If the main Goroutine exits, all other active Goroutines are terminated immediately.

Syntax:

func functionName() {
    // statements
}

// To execute as a Goroutine
go functionName()

Example:

package main

import "fmt"

func showMessage(msg string) {
    for i := 0; i < 3; i++ {
        fmt.Println(msg)
    }
}

func main() {
    go showMessage("Hello, Concurrent World!") // Executes concurrently
    showMessage("Hello from Main!")
}

Creating a Goroutine

To initiate a Goroutine, simply use the go keyword as a prefix when calling a function or method.

Syntax:

func functionName() {
    // statements
}

// Using `go` keyword to execute the function as a Goroutine
go functionName()

Example:

package main
import "fmt"

func printMessage(message string) {
    for i := 0; i < 3; i++ {
        fmt.Println(message)
    }
}

func main() {
    go printMessage("Welcome to Goroutines!") // Executes concurrently
    printMessage("Running in Main!")
}

Output:

Running in Main!
Running in Main!
Running in Main!

Running Goroutines with Delay

Incorporating time.Sleep() allows sufficient time for both the main and additional Goroutines to execute completely.

Example:

package main
import (
    "fmt"
    "time"
)

func printMessage(msg string) {
    for i := 0; i < 3; i++ {
        time.Sleep(300 * time.Millisecond)
        fmt.Println(msg)
    }
}

func main() {
    go printMessage("Executing in Goroutine!")
    printMessage("Executing in Main!")
}

Output:

Executing in Main!
Executing in Goroutine!
Executing in Goroutine!
Executing in Main!
Executing in Goroutine!
Executing in Main!

Anonymous Goroutines

You can also run anonymous functions as Goroutines by appending the go keyword before the function.

Syntax

go func(parameters) {
    // function body
}(arguments)

Example:

package main
import (
    "fmt"
    "time"
)

func main() {
    go func(msg string) {
        for i := 0; i < 3; i++ {
            fmt.Println(msg)
            time.Sleep(400 * time.Millisecond)
        }
    }("Anonymous Goroutine Execution!")

    time.Sleep(1.5 * time.Second) // Wait for Goroutine to complete
    fmt.Println("Main Goroutine Ends.")
}

Output:

Anonymous Goroutine Execution!
Anonymous Goroutine Execution!
Anonymous Goroutine Execution!
Main Goroutine Ends.
End of lesson.