Go Channel(for IPC)
we can send/recv data values via channel with operator, <-. The data
flows in the direction of the arrow.
ch <- v // Send v to channel ch.
v := <-ch // Receive from ch, and
// assign value to v.
Creating a channel
ch := make(chan int)
close(channel)
Only sender can close a channel to indicate that no more values will be
sent.
// Reciever can check if channel is closed?
v, ok := <-ch
if ok == false {
// channel is closed
}
// Reading all values from channel until it is closed
for v := range ch {
fmt.Println(v)
}
select(wait on multiple channels)
Channels need not to be closed because channels are not files; you don't
need to close them
Code
1. Write/Read data on channels
package main
import (
"fmt"
)
func main() {
// 1. Declare ch1,ch2,done unbuffered channels
ch1 := make(chan int)
ch2 := make(chan int)
done := make(chan int)
// 2. go routine. Send data on channels
go func() {
ch1 <- 1
ch2 <- 2
close(done)
}()
// 3. Keep waiting on channels
for {
select {
case v1, ok := <-ch1:
// Check channel is not closed
if ok {
fmt.Println("ch1:", v1)
}
case v2, ok := <-ch2:
if ok {
fmt.Println("ch2:", v2)
}
case <-done:
fmt.Println("Bye!")
return
default:
// Print this, when no channel is ready
fmt.Println("No case ready")
}
}
}
$ go run main.go
ch1: 1
ch2: 2
Bye!
Types of Channels
1. Buffered / Bounded
When buffer length is provided a buffered channel is created. Sends to a
buffered channel block only when the buffer is full. Receives block when
the buffer is empty.
ch := make(chan int, 100)
2. Unbuffered / Unbounded
Channel created without any size
ch := make(chan int)