怎么使用Golang中的select语句实现并发编程
这篇文章主要讲解了“怎么使用Golang中的select语句实现并发编程”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么使用Golang中的select语句实现并发编程”吧!
序文
select 是用来配合channel使用的
空select
没有内容的select 会阻塞
没有内容是指,没有case,也没有default
如果没有其它的任务指执行,将会触发死锁
packagemainimport("fmt""time")/***没有内容的select会阻塞*没有内容是指,没有case,也没有default*如果没有其它的任务指执行,将会触发死锁*/funcmain(){gofunc(){time.Sleep(2*time.Second)fmt.Println("没有内容的select会阻塞")}()select{}}只有default的select
只有default的select 和串行化没有区别
packagemainimport"fmt"/**只有default的select和串行化没有区别*/funcmain(){gofunc(){fmt.Println("quick")}()select{default:fmt.Println("end")}}
带 case 的 select
有case,有 default
如果能匹配到case 就 执行 case
匹配不到case,就执行default
有 default,就代表了不会阻塞
packagemainimport("fmt")funcmain(){ch2:=make(chanint,2)ch3:=make(chanint,2)select{casev1:=<-ch2:fmt.Println(v1)casev2:=<-ch3:fmt.Println(v2)default:fmt.Println(22)}}packagemainimport("fmt""time")funcmain(){ch2:=make(chanint,2)ch3:=make(chanint,2)gofunc(){ch2<-1}()time.Sleep(1*time.Second)select{casev1:=<-ch2:fmt.Printf("getv1chanvalue%d",v1)casev2:=<-ch3:fmt.Printf("getv1chanvalue%d",v2)default:fmt.Println(22)}}
有case,无default
会阻塞 一直等到case匹配上
packagemainimport("fmt""time")funcmain(){ch2:=make(chanint,2)ch3:=make(chanint,2)fmt.Printf("startunix:%d\n",time.Now().Unix())gofunc(){time.Sleep(3*time.Second)ch2<-1}()select{casev1:=<-ch2:fmt.Printf("caseunix:%d\n",time.Now().Unix())fmt.Printf("getv1chanvalue%d\n",v1)casev2:=<-ch3:fmt.Printf("getv1chanvalue%d\n",v2)}fmt.Println("end")}
select 只匹配一次,如果要进行 n > 1 的 匹配,使用 for + select
packagemainimport("fmt""time")funcmain(){ch2:=make(chanint,2)ch3:=make(chanint,2)fmt.Printf("startunix:%d\n",time.Now().Unix())gofunc(){for{time.Sleep(1*time.Second)ch2<-1}}()for{select{casev1:=<-ch2:fmt.Printf("caseunix:%d\n",time.Now().Unix())fmt.Printf("getv1chanvalue%d\n",v1)casev2:=<-ch3:fmt.Printf("getv1chanvalue%d\n",v2)}}}
匹配是无序的
packagemainimport("fmt""time")functest(){ch2:=make(chanint)ch3:=make(chanint)gofunc(){ch2<-1close(ch2)}()gofunc(){time.Sleep(1*time.Second)ch3<-1close(ch3)}()time.Sleep(2*time.Second)//如果有顺序,那么因该每次都是v1select{casev1:=<-ch2:fmt.Printf("caseunix:%d\n",time.Now().Unix())fmt.Printf("getv1chanvalue%d\n",v1)casev2:=<-ch3:fmt.Printf("caseunix:%d\n",time.Now().Unix())fmt.Printf("getv2chanvalue%d\n",v2)}}funcmain(){fori:=0;i<10;i++{test()}}
感谢各位的阅读,以上就是“怎么使用Golang中的select语句实现并发编程”的内容了,经过本文的学习后,相信大家对怎么使用Golang中的select语句实现并发编程这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!