Sobes.tech
Junior — Middle

Kuidas realiseeritakse paralleelsed arvutused Go keeles?

sobes.tech AI

Vastus AI-lt

In the Go language, parallel computations are implemented using goroutines (goroutines) and channels (channels).

Goroutines are lightweight threads that are started with the keyword go. They allow functions to be executed asynchronously and in parallel.

Example of parallel launching of two functions:

func task(id int) {
    fmt.Printf("Task %d started\n", id)
    // simulate work
    time.Sleep(time.Second)
    fmt.Printf("Task %d finished\n", id)
}

func main() {
    go task(1)
    go task(2)
    time.Sleep(2 * time.Second) // to allow goroutines to complete
}

Channels are used for synchronization and data transfer between goroutines, enabling safe exchange of information without blocking.

Thus, Go provides simple and efficient means for organizing parallel computations.