Channels & Select Operations
Channels allow goroutines to communicate and synchronize data safely, avoiding shared-memory race conditions.
1 Channels: Communication pipelines (ch <- val)
Go implements communication safety using channels: **"Do not communicate by sharing memory; instead, share memory by communicating."**
- `ch <- val`: Sends a value into a channel.
- `val := <-ch`: Receives a value from a channel.
- Synchronization: Unbuffered channel operations block execution automatically until both sender and receiver are ready, synchronizing the threads without using locks.
2 Channels Code
Let's run a program communicating values between threads using channels:
Go — Channels
▶ Run Code
package main
import "fmt"
func computeSum(a, b int, ch chan int) {
sum := a + b
ch <- sum // Send calculated sum into channel
}
func main() {
// Initialize channel of integers using make
ch := make(chan int)
// Launch worker goroutine
go computeSum(15, 25, ch)
// Receive value from channel (blocks main thread until value is sent)
result := <-ch
fmt.Println("Result received from channel: ", result)
}
3 Code Challenge
Challenge: Write a program that creates a string channel. Launch a goroutine that sends a message ("Greetings from worker!") into the channel. Receive the message in `main()` and print it.