Creation and usage
channel := make(chan type)
// send to channel
go func() { channel <- val1 }()
go func() { channel <- val2 }()
...
// receive
first := <-channel
second := <-channel
...Buffered vs Unbuffered channels
Unbuffered: Channels will block when sending until a reader is available Buffered: channels have a specific capacity and can send messages up to that capacity even without a reader
Buffered example
channel := make(chan int, BUFFER_SIZE)
// these will be buffered
channel <- 1
channel <- 2
go func() { channel <- 3}() // this will wait until 1 is read to be placed in the channelSelect keyword
- Allows you to work with two potentially blocking channels
- If one is blocking then reads from 2 and vice versa
one := make(chan int)
two := make(chan int)
for {
select {
case o := <-one:
fmt.Println(o)
case t := <-two
fmt.Println(t)
default:
fmt.Println("No data received")
}
// timeout case
select {
case o := <-one:
fmt.Println(o)
case t := <-two:
fmt.Printn(t)
case <-time.After(300 * time.Millisecond):
fmt.Println("timed out")
return
}
}