Go Goroutines: Multi-Threading Guide

In Go language, the concept of multi-threading is known as Goroutine. Goroutines are lightweight threads managed by Go’s runtime system. Creating a Goroutine is very simple, just add the keyword “go” before the function call. Here is a simple example:

package main

import (
    "fmt"
    "time"
)

func sayHello() {
    for i := 0; i < 5; i++ {
        fmt.Println("Hello")
        time.Sleep(1 * time.Second)
    }
}

func main() {
    go sayHello()
    time.Sleep(3 * time.Second)
    fmt.Println("Main function")
}

In the example above, we created a Goroutine to execute the function sayHello(), and used the “go” keyword in the main function to start this Goroutine. In the sayHello() function, we looped to print “Hello” and slept for 1 second, while in the main function, we printed “Main function” and slept for 3 seconds.

By this example, we can see that using Goroutines is very simple. Just add the “go” keyword before a function call to create a new Goroutine to execute the function concurrently. This concurrent execution can improve the performance and efficiency of the program.

bannerAds