1、未使用go channel
package main import ( "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.go h w e o l r l l o d exit status 2
2、使用channel
package main import ( "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.go h e l l o w o r l d
3、小结
channel 有两端,一端写入(数据传入)ch<- ;一端读出(传出数据);要求读写两端必须同时满足条件,才能在channel上完成数据流动,否则阻塞。
4、 关闭channel
package main import "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.go 0 1 2 3 4 5 6 7 channel close d:\goprojects\src\day1\并发\exp1>