go channel 理解
1、未使用go channel
package mainimport ( "fmt" "time")func printer(s string) { for _, v := range s { fmt.Println(string(v)) time.Sleep(time.Millisecond * 3000) }}func person() { printer("hello")}func person2() { printer("world")}func main() { go person() go person2() for { }}
d:\goprojects\src\day1\练习>go run main.gohweolrllodexit status 2
2、使用channel
package mainimport ( "fmt" "time")var ch = make(chan int, 1)func printer(s string) { for _, v := range s { fmt.Println(string(v)) time.Sleep(time.Millisecond * 3000) }}func person() { printer("hello") ch <- 1}func person2() { <-ch printer("world")}func main() { go person() go person2() for { }}
d:\goprojects\src\day1\练习>go run main.gohelloworld
3、小结
channel 有两端,一端写入(数据传入)ch<- ;一端读出(传出数据);要求读写两端必须同时满足条件,才能在channel上完成数据流动,否则阻塞。
4、 关闭channel
package mainimport "fmt"func main() { ch := make(chan int) go func() { for i := 0; i < 8; i++ { ch <- i } close(ch) }() for { if num, ok := <-ch; ok { fmt.Println(num) } else { fmt.Println("channel close") break } }}
d:\goprojects\src\day1\并发\exp1>go run main.go01234567channel closed:\goprojects\src\day1\并发\exp1>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。