Junior — Middle
Vazifa bajarishning raqobat muhitida goroutinlarni sinxronlashtirish mexanizmining ishlash prinsipi haqida tushuntiring.
sobes.tech AI
AIdan javob
In Go, goroutines are lightweight threads that run concurrently. Synchronization of goroutines is achieved using mechanisms that coordinate access to shared resources and order execution.
Main synchronization mechanisms:
- Channels: allow data transfer between goroutines, ensuring synchronization through message exchange.
- Mutexes (sync.Mutex): block access to shared data to prevent race conditions.
- WaitGroup (sync.WaitGroup): allows waiting for a group of goroutines to finish.
Example with a channel:
package main
import (
"fmt"
)
func worker(ch chan int) {
val := <-ch // waits for data from the channel
fmt.Println("Received value:", val)
}
func main() {
ch := make(chan int)
go worker(ch)
ch <- 42 // sends data into the channel
}
Here, the channel ensures synchronization: the worker goroutine waits until main sends a value.