Junior — Middle
Kuidas Golang tagab täitmisniitide töö ja sünkroniseerimise?
sobes.tech AI
Vastus AI-lt
In Go, to work with execution streams, goroutines are used — lightweight threads managed by the Go runtime. Goroutines are started with the go keyword before calling a function, allowing them to run asynchronously.
To synchronize goroutines, channels and primitives from the sync package (such as Mutex, WaitGroup) are used. Channels provide safe data exchange between goroutines and enable their synchronization.
Example of using goroutines and channels:
package main
import (
"fmt"
"time"
)
func worker(ch chan string) {
time.Sleep(time.Second)
ch <- "done"
}
func main() {
ch := make(chan string)
go worker(ch)
msg := <-ch
fmt.Println("Goroutine work:", msg)
}
Here, the main goroutine starts worker in a separate goroutine, which after a delay sends a message through the channel. The main goroutine waits to receive the message from the channel, ensuring synchronization.