Channel Communication
Communication Patterns
1. Producer-Consumer Model
func producerConsumer() {
jobs := make(chan int, 100)
results := make(chan int, 100)
// Worker goroutines
for w := 1; w <= 3; w++ {
go func(id int) {
for job := range jobs {
results <- job * 2
}
}(w)
}
// Send jobs
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// Collect results
for a := 1; a <= 5; a++ {
<-results
}
}
Communication Flow Visualization
graph LR
A[Producer] -->|Send Data| B{Channel}
B -->|Receive Data| C[Consumer]
B -->|Broadcast| D[Multiple Consumers]
Channel Communication Types
Communication Type |
Description |
Use Case |
Synchronous Communication |
Blocking send and receive |
Precise data exchange |
Asynchronous Communication |
Buffered channels |
High-performance scenarios |
Signaling |
Closing channels |
Goroutine coordination |
Synchronization Techniques
1. Signaling with Channels
func coordinateGoroutines() {
done := make(chan bool)
go func() {
// Perform task
done <- true
}()
<-done // Wait for completion
}
2. Fan-Out Pattern
func fanOutCommunication() {
data := make(chan int)
// Multiple receivers
for i := 0; i < 3; i++ {
go func(id int) {
for value := range data {
fmt.Printf("Worker %d received %d\n", id, value)
}
}(i)
}
// Send data to multiple workers
for j := 0; j < 10; j++ {
data <- j
}
close(data)
}
Advanced Communication Patterns
Bidirectional Channel Communication
func bidirectionalCommunication(ch chan<- int, done <-chan bool) {
for {
select {
case <-done:
return
case ch <- rand.Intn(100):
time.Sleep(time.Millisecond * 500)
}
}
}
Error Handling in Channel Communication
func communicationWithErrorHandling() {
results := make(chan int)
errors := make(chan error)
go func() {
defer close(results)
defer close(errors)
// Perform operation
if err != nil {
errors <- err
return
}
results <- computedValue
}()
select {
case result := <-results:
fmt.Println("Success:", result)
case err := <-errors:
fmt.Println("Error:", err)
}
}
Channel Communication Best Practices
- Use channels for communication, not for sharing memory
- Close channels when no more data will be sent
- Avoid goroutine leaks
- Use buffered channels judiciously
graph TD
A[Channel Communication] --> B{Buffered vs Unbuffered}
B -->|Buffered| C[Higher Performance]
B -->|Unbuffered| D[Strict Synchronization]
LabEx Learning Approach
At LabEx, we recommend hands-on practice with channel communication patterns to develop robust concurrent programming skills in Go.