Skip to content

Instantly share code, notes, and snippets.

@tenfyzhong
Last active June 2, 2022 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tenfyzhong/0fc5819f4885d4a8877659ca24361f09 to your computer and use it in GitHub Desktop.
Save tenfyzhong/0fc5819f4885d4a8877659ca24361f09 to your computer and use it in GitHub Desktop.
有没buffer的channel例子代码
package main
import (
"log"
"time"
)
func chan0SendOnly() {
c0 := make(chan bool)
log.Println("c0, sending")
c0 <- true
log.Println("c0, send success")
}
func chan1SendRecv() {
c1 := make(chan bool)
go func() {
log.Println("c1, sending")
c1 <- true
log.Println("c1, send success")
}()
go func() {
log.Println("c1, receiving")
time.Sleep(2 * time.Second)
<-c1
log.Println("c1, recv success")
}()
}
func chan2SendOnly() {
c2 := make(chan bool, 1)
log.Println("c2, sending")
c2 <- true
log.Println("c2, send success")
}
func chan3SendRecv() {
c3 := make(chan bool, 1)
go func() {
log.Println("c3, sending")
c3 <- true
log.Println("c3, send success")
}()
go func() {
log.Println("c3, receiving")
time.Sleep(2 * time.Second)
<-c3
log.Println("c3, recv success")
}()
}
func main() {
go chan0SendOnly()
time.Sleep(1 * time.Second)
go chan1SendRecv()
time.Sleep(3 * time.Second)
go chan2SendOnly()
time.Sleep(1 * time.Second)
go chan3SendRecv()
time.Sleep(3 * time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment