func main() {
c:= make(chan bool)
go waitAndSay(c, "world")
fmt.Println("Hello")
//we send a signal to c in order to allow waitAndSay to continue
c<- true
//we wait to receive another signal on c before we exit
<-c
}
func waitAndSay(c chan bool, s string) {
if b := <-c; b {
fmt.Println(s)
}
c <- true
}
func main() {
ch := make(chan string, 2)
ch <- "Hello"
ch <- "World"
fmt.Println(<-ch)
fmt.Println(<-ch)
}
Hello
World
func main() {
ch := make(chan string, 2)
ch <- "Hello"
ch <- "World"
ch <- "Hello again"
fmt.Println(<-ch)
fmt.Println(<-ch)
}
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
C:/Users/7205033/Documents/Go/Learngo/Udemy/gochannel/main.go:50 +0x5c
exit status 2
func main() {
c := make(chan string)
go SayHelloMultipleTimes(c, 5)
for s := range c {
fmt.Println(s)
}
v, ok := <-c
fmt.Println("Channel close?", !ok, " value ", v)
}
func SayHelloMultipleTimes(c chan string, n int) {
for i := 0; i <= n; i++ {
c <- "Hello"
}
close(c)
}
Hello
Hello
Hello
Hello
Hello
Hello
Channel close? true value
-Likewise, when data is received, if there is no data transmitted and data is received from the channel, it enters the infinite standby state. However, if you close the channel after sending data to the channel at this time, you can no longer transmit data to the corresponding channel, but you can continue to receive after the channel is closed. To close a channel, use the "close(channelname)" format.