标签:golang goroutine channel select
goroutine
package main import "fmt" import "time" func printn(id int){ for i := 0;i<10;i++ { fmt.Println(id,":",i) } } func main(){ for i :=0;i<5;i++ { go printn(i) } fmt.Println("waiting...") time.Sleep(time.Second * 3) } //执行结果: waiting... 0 : 0 2 : 0 0 : 1 2 : 1 0 : 2 1 : 0 2 : 2 0 : 3 2 : 3 1 : 1 0 : 4 2 : 4 0 : 5 1 : 2 2 : 5 0 : 6 1 : 3 2 : 6 0 : 7 1 : 4 2 : 7 1 : 5 3 : 0 3 : 1 3 : 2 2 : 8 1 : 6 2 : 9 1 : 7 3 : 3 0 : 8 0 : 9 1 : 8 3 : 4 3 : 5 3 : 6 3 : 7 3 : 8 3 : 9 1 : 9 4 : 0 4 : 1 4 : 2 4 : 3 4 : 4 4 : 5 4 : 6 4 : 7 4 : 8 4 : 9 // 如果把sleep去掉会怎么样? package main import "fmt" //import "time" func printn(id int){ for i := 0;i<10;i++ { fmt.Println(id,":",i) } } func main(){ for i :=0;i<5;i++ { go printn(i) } fmt.Println("waiting...") //time.Sleep(time.Second * 3) } // 执行结果: waiting... //原因是没有sleep,当main函数执行完会中断其他所有没执行完的任务
2、channel
package main import "fmt" //import "time" func printn(id int,c chan int){ for i := 0;i<10;i++ { fmt.Println(id,":",i) } c <- 0 //将数值存到 c } func main(){ c :=make(chan int) // 创建一个channel go printn(1,c) // for i :=0;i<5;i++ { // go printn(i) // } fmt.Println("waiting...") //time.Sleep(time.Second * 3) <- c // 取出c得值 } // 执行结果: waiting... 1 : 0 1 : 1 1 : 2 1 : 3 1 : 4 1 : 5 1 : 6 1 : 7 1 : 8 1 : 9
3、select
package main import "fmt" import "time" func fun1(c chan string){ for { c <- "from fun1 +" time.Sleep(time.Second * 2) } } func fun2(c chan string){ for { c <- "from fun2 -" time.Sleep(time.Second * 2) } } func main(){ c1 :=make(chan string) c2 :=make(chan string) go fun1(c1) go fun2(c2) for { select { case msg1 := <- c1: fmt.Println(msg1) case msg2 := <- c2: fmt.Println(msg2) } } } // 执行结果: from fun2 - from fun1 + from fun2 - from fun1 + from fun1 + from fun2 - from fun2 - from fun1 + from fun1 + from fun2 - ...........
本文出自 “欺壹世De博客” 博客,请务必保留此出处http://qiyishi.blog.51cto.com/5731577/1903692
golang goroutine、channel和select
标签:golang goroutine channel select
原文地址:http://qiyishi.blog.51cto.com/5731577/1903692