Sobes.tech
Junior — Middle

Kuidas toimub uue gorutina initsialiseerimine ja täitmine programmis?

sobes.tech AI

Vastus AI-lt

In the Go language, a new goroutine is created using the keyword go, followed by a function or method call. This creates a lightweight execution thread that runs in parallel with the main program.

The initialization and start of a goroutine are done as follows:

  1. Call go before the function: go myFunction().
  2. The Go scheduler creates a new goroutine and puts it in the execution queue.
  3. The goroutine begins executing asynchronously, independently of the main program.

Example:

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

func main() {
    go sayHello() // start the goroutine
    fmt.Println("Hello from main")
    time.Sleep(time.Second) // give the goroutine time to finish
}

It is important to remember that goroutines are very lightweight compared to OS threads, and their scheduling and context switching are managed by the Go runtime, which allows efficient resource utilization.