Created
February 28, 2016 16:53
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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