How is concurrency and synchronization modeled in Go?
sobes.tech AI
Answer from AI
In the Go language, concurrency is implemented through lightweight threads called goroutines. Goroutines are started using the go keyword and run in parallel, with the Go runtime managing their scheduling.
Several mechanisms are used for synchronization and data exchange between goroutines:
-
Channels — allow safe data transfer between goroutines, providing synchronization. Channels can be thought of as queues that block the sender if the channel is full and the receiver if the channel is empty.
-
sync package — contains synchronization primitives such as mutexes (
sync.Mutex), condition variables (sync.Cond), wait groups (sync.WaitGroup), and others.
Example of using goroutines and channels:
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)
}
}
Here, three goroutines run in parallel, and a channel is used to receive results from each of them.