2017-05-28 21:17:32 +00:00
|
|
|
ch := make(chan int) // create a channel of type int
|
|
|
|
ch <- 42 // Send a value to the channel ch.
|
|
|
|
v := <-ch // Receive a value from ch
|
|
|
|
|
|
|
|
// Create a buffered channel.
|
2020-02-22 02:47:54 +00:00
|
|
|
// Writing to a buffered channels does not block
|
2017-05-28 21:17:32 +00:00
|
|
|
// if less than <buffer size> unread values have been written.
|
|
|
|
ch := make(chan int, 100)
|
|
|
|
// Non-buffered channels block.
|
|
|
|
// Read blocks when no value is available,
|
|
|
|
// write blocks if a value already has been written but not read.
|
|
|
|
|
|
|
|
close(ch) // closes the channel (only sender should close)
|
|
|
|
|
|
|
|
// read from channel and test if it has been closed
|
|
|
|
v, ok := <-ch
|
|
|
|
// if ok is false, channel has been closed
|
|
|
|
|
|
|
|
// Read from channel until it is closed
|
|
|
|
for i := range ch {
|
|
|
|
fmt.Println(i)
|
|
|
|
}
|
|
|
|
|
|
|
|
// select blocks on multiple channel operations,
|
|
|
|
// if one unblocks, the corresponding case is executed
|
|
|
|
func doStuff(channelOut, channelIn chan int) {
|
|
|
|
select {
|
|
|
|
case channelOut <- 42:
|
|
|
|
fmt.Println("We could write to channelOut!")
|
|
|
|
case x := <- channelIn:
|
|
|
|
fmt.Println("We could read from channelIn")
|
|
|
|
case <-time.After(time.Second * 1):
|
|
|
|
fmt.Println("timeout")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|