Sobes.tech
Junior — Middle

What actions are performed when two goroutines write to a channel simultaneously?

sobes.tech AI

Answer from AI

In Go, when two goroutines write to a channel simultaneously, synchronization occurs through the channel itself. The channel guarantees that write and read operations happen atomically and sequentially.

If two goroutines attempt to write to the channel at the same time, one will be blocked until the other completes the write. Thus, writes do not get mixed or lost — each write will enter the channel in order.

Example:

ch := make(chan int)

// Goroutine 1
go func() {
    ch <- 1 // write to channel
}()

// Goroutine 2
go func() {
    ch <- 2 // write to channel
}()

// Reading from the channel
fmt.Println(<-ch)
fmt.Println(<-ch)

In this example, both writes will be correctly placed into the channel, the order can be any, but the data will not be lost or mixed.