Skip to content

Instantly share code, notes, and snippets.

@gerep
Created February 28, 2016 16:53
Show Gist options
  • Save gerep/17e3c71f6ed5f8a066fe to your computer and use it in GitHub Desktop.
Save gerep/17e3c71f6ed5f8a066fe to your computer and use it in GitHub Desktop.
On buffered channels, all read operations will not block if the buffer is not empty and the write operation if the buffer is not full
// This code will return a deadlock error.
// Since the channel c is unbuffered, the write operation c<-42 (writing 42 to the channel) will block.
package main
func main() {
c := make(chan int)
c <- 42
val := <-c
println(val)
}
// A buffered channel will store the integers without waiting for a read operation
package main
func main() {
c := make(chan int, 1)
c <- 42
val := <-c
println(val)
}
// Without a buffered channel but running the write operation on another thread
package main
func main() {
c := make(chan int)
go func() {
c <- 42
}()
val := <-c
println(val)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment