Sobes.tech
Senior

Fill a slice with elements without a mutex so that it contains all 1000 elements.

sobes.tech AI

Answer from AI

To fill a slice of 1000 elements in parallel without using a mutex, you can pre-allocate a slice of the required size and distribute the indices among goroutines so that each writes to a unique section of the slice. This way, data races will not occur, as each element is written by only one goroutine.

Example:

package main

import (
	"fmt"
	"sync"
)

func main() {
	size := 1000
	slice := make([]int, size)

	var wg sync.WaitGroup
	workers := 10
	chunkSize := size / workers

	for w := 0; w < workers; w++ {
		start := w * chunkSize
		end := start + chunkSize
		if w == workers-1 {
			end = size // last worker can take the remainder
		}

		wg.Add(1)
		go func(s, e int) {
			defer wg.Done()
			for i := s; i < e; i++ {
				slice[i] = i * 2 // example filling
			}
		}(start, end)
	}

	wg.Wait()

	fmt.Println("Slice length:", len(slice))
	fmt.Println("First 10 elements:", slice[:10])
}

Here, each goroutine writes to its part of the slice, so a mutex is not needed.

Fill a slice with elements without a mutex so that it… - sobes.tech