Sobes.tech
Junior — Middle

How are competition, asynchrony, and parallelism implemented in the Go language?

sobes.tech AI

Answer from AI

In Go, concurrency, asynchronous execution, and parallelism are implemented using goroutines and channels.

  • Goroutines are lightweight threads that are started with the go keyword. They allow functions to run asynchronously and compete for resources.
  • Channels are used for safe data exchange between goroutines, providing synchronization and message passing.

Parallelism is achieved by running multiple goroutines that can execute simultaneously on multiple CPU cores if GOMAXPROCS is set.

Example:

package main
import (
    "fmt"
    "time"
)

func worker(id int, ch chan string) {
    time.Sleep(time.Second)
    ch <- fmt.Sprintf("Worker %d done", id)
}

func main() {
    ch := make(chan string)
    for i := 1; i <= 3; i++ {
        go worker(i, ch) // start goroutine
    }
    for i := 1; i <= 3; i++ {
        msg := <-ch // receive result from channel
        fmt.Println(msg)
    }
}

Thus, Go provides simple and efficient tools for working with concurrency and parallelism.