Middle — Middle+
What approaches can be used to ensure thread safety when working with slices in a multithreaded environment?
sobes.tech AI
Answer from AI
In Go, slices are not thread-safe by default, so when working with them in a multithreaded environment, synchronization must be used.
Main approaches:
- Mutex (sync.Mutex) — the most common method. Wrap read and write operations in mutex blocks to avoid data races.
var mu sync.Mutex
var s []int
func appendValue(v int) {
mu.Lock()
s = append(s, v)
mu.Unlock()
}
func readSlice() []int {
mu.Lock()
defer mu.Unlock()
return append([]int(nil), s...) // copy of the slice
}
-
sync.RWMutex — if there are many read operations and few writes, RWMutex can be used to improve performance.
-
Copying the slice — to avoid races, working with copies of the slice is possible, but not always efficient.
-
Channels — access to the slice can be organized through a goroutine manager that receives commands via a channel and modifies the slice, ensuring sequential access.
type command struct {
op string
val int
resp chan []int
}
func sliceManager(cmds chan command) {
var s []int
for cmd := range cmds {
switch cmd.op {
case "append":
s = append(s, cmd.val)
case "read":
cmd.resp <- append([]int(nil), s...)
}
}
}
The choice of approach depends on specific performance requirements and code complexity.