Middle
What can and cannot be done with thread safety in channels in Go?
sobes.tech AI
Answer from AI
Can:
- Send and receive data. Each read and write operation on a channel is atomic.
- Close a channel. Closing signals that no more data will be sent.
- Use the
selectstatement for non-blocking interactions with multiple channels. - Use buffered and unbuffered channels for different synchronization scenarios.
Cannot:
- Close a channel from multiple goroutines simultaneously without additional synchronization. This can lead to a panic.
- Close an already closed channel. This will also cause a panic.
- Send data to a closed channel. This will cause a panic.
- Wait for a read from a nil (uninitialized) channel. This will block the goroutine.
- Wait for a write to a nil (uninitialized) channel. This will block the goroutine.
Example of channel usage:
// Create an unbuffered channel for int
to be used for message passing
messages := make(chan int)
// Goroutine for sending data
go func() {
messages <- 1 // Send 1 to the channel
messages <- 2 // Send 2 to the channel
close(messages) // Close the channel after sending
}()
// Reading data from the channel
firstMessage := <-messages
secondMessage := <-messages
// Reading from a closed channel returns the zero value and ok=false
value, ok := <-messages