Sobes.tech
Junior — Middle

Kuidas rakendatakse goroutine-mehhanismi programmeerimises ja millist rolli see täidab?

sobes.tech AI

Vastus AI-lt

Goroutines in Go are lightweight threads that allow functions to run in parallel without significant resource costs. They are managed by the Go runtime and created using the go keyword.

The main role of goroutines is to simplify concurrent and parallel programming, enabling efficient use of multi-processor systems and avoiding blocking the main thread.

Example of using a goroutine:

package main

import (
    "fmt"
    "time"
)

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

func main() {
    go sayHello() // start function in a goroutine
    time.Sleep(time.Second) // wait for the goroutine to complete
    fmt.Println("Main function finished")
}

In this example, sayHello runs in parallel with the main main function.