Junior — Middle
How is the management of competing threads or processes implemented in the program?
sobes.tech AI
Answer from AI
In Go, managing concurrent threads (goroutines) is implemented using built-in primitives:
- Goroutines — lightweight threads that are started with the
gokeyword. - Channels — used for safe data exchange between goroutines and synchronization.
Example of concurrency management:
package main
import (
"fmt"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, j)
time.Sleep(time.Second) // simulate work
results <- j * 2
}
}
func main() {
jobs := make(chan int, 5)
results := make(chan int, 5)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
for a := 1; a <= 5; a++ {
fmt.Println("Result:", <-results)
}
}
Thus, concurrency management in Go is built on simple and powerful primitives that allow writing safe and efficient parallel code.