golang select 選取器的兩種方案

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

golang select 選取器



常規模式:

package mainimport ("fmt""strconv")func main() {var chs1 = make(chan int)var chs2 = make(chan float64)var chs3 = make(chan string)var ch4close = make(chan int)defer close(ch4close)go func(c chan int, ch4close chan int) {for i := 0; i < 5; i++ {c <- i}close(c)ch4close <- 1}(chs1, ch4close)go func(c chan float64, ch4close chan int) {for i := 0; i < 5; i++ {c <- float64(i) + 0.1}close(c)ch4close <- 1}(chs2, ch4close)go func(c chan string, ch4close chan int) {for i := 0; i < 5; i++ {c <- "string:" + strconv.Itoa(i)}close(c)ch4close <- 1}(chs3, ch4close)done := 0finished := 0for finished < 3 {select {case v, ok := <-chs1:if ok {done = done + 1fmt.Println(0, v)}case v, ok := <-chs2:if ok {done = done + 1fmt.Println(1, v)}case v, ok := <-chs3:if ok {done = done + 1fmt.Println(2, v)}case _, ok := <- ch4close:if ok {finished = finished+1}}}fmt.Println("Done", done)}


reflect設計


package mainimport ("fmt""reflect""strconv")func main() {var chs1 = make(chan int)var chs2 = make(chan float64)var chs3 = make(chan string)var ch4close = make(chan int)defer close(ch4close)go func(c chan int, ch4close chan int) {for i := 0; i < 5; i++ {c <- i}close(c)ch4close <- 1}(chs1, ch4close)go func(c chan float64, ch4close chan int) {for i := 0; i < 5; i++ {c <- float64(i) + 0.1}close(c)ch4close <- 1}(chs2, ch4close)go func(c chan string, ch4close chan int) {for i := 0; i < 5; i++ {c <- "string:" + strconv.Itoa(i)}close(c)ch4close <- 1}(chs3, ch4close)var selectCase = make([]reflect.SelectCase, 4)selectCase[0].Dir = reflect.SelectRecvselectCase[0].Chan = reflect.ValueOf(chs1)selectCase[1].Dir = reflect.SelectRecvselectCase[1].Chan = reflect.ValueOf(chs2)selectCase[2].Dir = reflect.SelectRecvselectCase[2].Chan = reflect.ValueOf(chs3)selectCase[3].Dir = reflect.SelectRecvselectCase[3].Chan = reflect.ValueOf(ch4close)done := 0finished := 0for finished < len(selectCase)-1 {chosen, recv, recvOk := reflect.Select(selectCase)if recvOk {done = done+1switch chosen {case 0:fmt.Println(chosen, recv.Int())case 1:fmt.Println(chosen, recv.Float())case 2:fmt.Println(chosen, recv.String())case 3:finished = finished+1done = done-1// fmt.Println("finished\t", finished)}}}fmt.Println("Done", done)}



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.