Junior — Middle
How can data races that occur during concurrent access to resources in a multithreaded environment be eliminated?
sobes.tech AI
Answer from AI
To eliminate data races in a multi-threaded environment in Go, several approaches can be used:
-
Mutexes (sync.Mutex) — block access to shared resources, allowing only one goroutine to work with it at a time.
-
Channels — enable safe data exchange between goroutines, avoiding direct access to shared variables.
-
sync/atomic package — provides atomic operations for primitive types, helping to avoid races during simple operations.
Example with a mutex:
import (
"sync"
)
var mu sync.Mutex
var counter int
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
Using channels:
ch := make(chan int)
func worker() {
for val := range ch {
// process val
}
}
func main() {
go worker()
ch <- 42
close(ch)
}
The choice of method depends on the specific task and program structure.