golang select 代码示例

package main

import "fmt"

func main() {
   var c1, c2, c3 chan int
   var i1, i2 int
   select {
      case i1 = <-c1:
         fmt.Printf("received %#v %s", i1, " from c1\n")
      case c2 <- i2:
         fmt.Printf("sent %#v %s", i2, " to c2\n")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            fmt.Printf("received %#v %s", i3, " from c3\n")
         } else {
            fmt.Printf("c3 is closed\n")
         }
      default:
         fmt.Printf("no communication\n")
   }    
}

输出:

no communication
package main

import "fmt"

func main() {
   var c1, c2, c3 chan int
   var i1, i2 int
   select {
      case i1 = <-c1:
         fmt.Printf("received %#v %s", i1, " from c1\n")
      case c2 <- i2:
         fmt.Printf("sent %#v %s", i2, " to c2\n")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            fmt.Printf("received %#v %s", i3, " from c3\n")
         } else {
            fmt.Printf("c3 is closed\n")
         }
   }    
}

输出:无

fatal error: all goroutines are asleep - deadlock!
发布了1295 篇原创文章 · 获赞 170 · 访问量 398万+

猜你喜欢

转载自blog.csdn.net/wide288/article/details/103938949