Sobes.tech
Junior — Middle

How are parallel computations implemented in Go?

sobes.tech AI

Answer from AI

In the Go language, parallel computing is implemented using goroutines and channels.

Goroutines are lightweight threads that are launched using the go keyword. They allow functions to run asynchronously and in parallel.

An example of parallel execution 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 finish
}

Channels are used for synchronization and data transfer between goroutines, enabling safe communication without locks.

Thus, Go provides simple and effective tools for organizing parallel computations.