Senior
What primitive approach allows to write all values absolutely in parallel and correctly, considering we have a fixed array and a fixed number of goroutines?
sobes.tech AI
Answer from AI
If we have a fixed array and a fixed number of goroutines, and need to write all values in parallel and correctly, a primitive and efficient approach is to divide the work so that each goroutine writes to its unique index of the array. This eliminates data races and the need for synchronization.
Example:
type Data []int
func worker(data Data, start, end int, wg *sync.WaitGroup) {
defer wg.Done()
for i := start; i < end; i++ {
data[i] = i * 2 // or any other write logic
}
}
func main() {
size := 100
data := make(Data, size)
var wg sync.WaitGroup
numGoroutines := 5
chunkSize := size / numGoroutines
for i := 0; i < numGoroutines; i++ {
start := i * chunkSize
end := start + chunkSize
if i == numGoroutines-1 {
end = size
}
wg.Add(1)
go worker(data, start, end, &wg)
}
wg.Wait()
// data is now correctly filled
}
Thus, each goroutine is responsible for its section of the array, which guarantees correctness and parallelism without locks.