Sobes.tech
Junior — Middle

How is concurrency model implemented in the Go language?

sobes.tech AI

Answer from AI

In the Go language, the model of concurrency is based on goroutines and channels.

  • Goroutines are lightweight threads that are launched using the go keyword. They allow functions to run in parallel without significant resource costs.

  • Channels are typed conduits for data exchange between goroutines, providing synchronization and safe communication.

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)
    }

    for i := 1; i <= 3; i++ {
        msg := <-ch
        fmt.Println(msg)
    }
}

In this example, three goroutines perform work in parallel and send the result to a channel, from which the main thread reads.

Thus, Go simplifies concurrent programming by hiding the complexity of threads and synchronization.