Sobes.tech
Junior — Middle

How to ensure safe data recording into a channel from multiple goroutines without using locking?

sobes.tech AI

Answer from AI

In Go, to safely write data to a channel from multiple goroutines without using locks, it is usually sufficient to use the channel itself, as channels in Go are thread-safe by default.

Example:

ch := make(chan int)

// Writing to the channel from multiple goroutines
for i := 0; i < 5; i++ {
    go func(val int) {
        ch <- val // safe write
    }(i)
}

// Reading from the channel
for i := 0; i < 5; i++ {
    fmt.Println(<-ch)
}

If you need to guarantee that the write does not block, you can use a buffered channel. This way, manual locks are not needed, as the channel provides synchronization.