Sobes.tech
Junior — Middle

Kuidas luua ja käivitada eraldi täitmisniit Go-s?

sobes.tech AI

Vastus AI-lt

In Go, to create and start a separate thread, the keyword go is used, which runs the function as a goroutine — a lightweight thread.

Example:

package main

import (
    "fmt"
    "time"
)

func sayHello() {
    fmt.Println("Hello from goroutine!")
}

func main() {
    go sayHello() // start goroutine
    time.Sleep(time.Second) // give the goroutine time to execute
    fmt.Println("Main function finished")
}

In this example, the sayHello function runs in a separate goroutine, parallel to the main main function. To give the goroutine time to complete, a delay is added in main.