channel有缓冲与无缓冲同步问题
package main import ( "fmt" "time" ) func main() { c := make(chan int, 3) //带有缓冲的channel fmt.Println("len(c) = ", len(c), ", cap(c)", cap(c)) go func() { defer fmt.Println("子go程结束") for i := 0; i < 4; i++ { c <- i fmt.Println("子go程正在运行, 发送的元素=", i, " len(c)=", len(c), ", cap(c)=", cap(c)) } }() time.Sleep(2 * time.Second) for i := 0; i < 4; i++ { num := <-c //从c中接收数据,并赋值给num fmt.Println("num = ", num) } fmt.Println("main 结束") }
关闭channel
package main import "fmt" func main() { c := make(chan int) go func() { for i := 0; i < 5; i++ { c <- i //close可以关闭一个channel close(c) } }() for { //ok如果为true表示channel没有关闭,如果为false表示channel已经关闭 if data, ok := <-c; ok { fmt.Println(data) } else { break } } fmt.Println("Main Finished..") }