Sobes.tech
Junior — Middle

How is parallel processing and management of concurrent tasks implemented in Go?

sobes.tech AI

Answer from AI

In Go, parallel processing and management of concurrent tasks are implemented through goroutines and channels.

  • Goroutines are lightweight threads that are launched using the go keyword. They allow functions to run concurrently.

  • 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 run in parallel, and a channel is used to receive the results.

Thus, Go provides simple yet powerful tools for concurrent programming without the complexities of traditional threads.

How is parallel processing and management of… - sobes.tech