Add select...default
This commit is contained in:
parent
00b427a3ab
commit
c41662bff8
6
main.go
6
main.go
@ -7,7 +7,8 @@ package main
|
|||||||
// import "git.sangeeth.dev/gobyexample/goroutines"
|
// import "git.sangeeth.dev/gobyexample/goroutines"
|
||||||
// import "git.sangeeth.dev/gobyexample/channels"
|
// import "git.sangeeth.dev/gobyexample/channels"
|
||||||
// import "git.sangeeth.dev/gobyexample/cselect"
|
// import "git.sangeeth.dev/gobyexample/cselect"
|
||||||
import "git.sangeeth.dev/gobyexample/timeouts"
|
// import "git.sangeeth.dev/gobyexample/timeouts"
|
||||||
|
import "git.sangeeth.dev/gobyexample/selectdefault"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// runes.Runes()
|
// runes.Runes()
|
||||||
@ -17,5 +18,6 @@ func main() {
|
|||||||
// goroutines.Goroutines()
|
// goroutines.Goroutines()
|
||||||
// channels.Channels()
|
// channels.Channels()
|
||||||
// cselect.Select()
|
// cselect.Select()
|
||||||
timeouts.Timeouts()
|
// timeouts.Timeouts()
|
||||||
|
selectdefault.SelectDefault()
|
||||||
}
|
}
|
||||||
|
31
selectdefault/selectdefault.go
Normal file
31
selectdefault/selectdefault.go
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
package selectdefault
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func SelectDefault() {
|
||||||
|
msgs := make(chan string)
|
||||||
|
signals := make(chan string)
|
||||||
|
|
||||||
|
select {
|
||||||
|
case val := <-msgs:
|
||||||
|
fmt.Println("Received", val)
|
||||||
|
default:
|
||||||
|
fmt.Println("`default` can be used to prevent blocking when there's nothing to receive from a channel")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case msgs <- "hello":
|
||||||
|
fmt.Println("Sent hello")
|
||||||
|
default:
|
||||||
|
fmt.Println("`default` can be used to prevent blocking when we send something to an unbuffered channel but there's nobody to receive")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case val := <-msgs:
|
||||||
|
fmt.Println("Received something from msgs", val)
|
||||||
|
case val := <-signals:
|
||||||
|
fmt.Println("Received something from signals", val)
|
||||||
|
default:
|
||||||
|
fmt.Println("`default` can be used to prevent blocking when there's nothing to receive or if its not possible to send across multiple channels")
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user