zoukankan      html  css  js  c++  java
  • Select

    什么是 select?

    select 语句用于在多个发送/接收信道操作中进行选择。select 语句会一直阻塞,直到发送/接收操作准备就绪。
    如果有多个信道操作准备完毕,select 会随机地选取其中之一执行。
    该语法与 switch 类似,所不同的是,这里的每个 case 语句都是信道操作。我们好好看一些代码来加深理解吧。

    示例

    package main
    
    import (
        "fmt"
        "time"
    )
    
    //func server1(ch chan string) {
    //    time.Sleep(6 * time.Second)
    //    ch <- "from server1"
    //}
    //
    //
    //func server2(ch chan string) {
    //    time.Sleep(3 * time.Second)
    //    ch <- "from server2"
    //
    //}
    //
    //func main() {
    //    output1 := make(chan string)
    //    output2 := make(chan string)
    //    //开启两个协程执行server
    //    go server2(output1)
    //    go server2(output2)
    //    select {
    //    case s1 := <-output1:
    //        fmt.Println(s1,"ddddd")
    //    case s2 := <-output2:
    //        fmt.Println(s2,"yyyy")
    //    }
    //}
    
    //func process(ch chan string) {
    //    time.Sleep(10500 * time.Millisecond)
    //    ch <- "process successful"
    //}
    //
    //func main() {
    //    ch := make(chan string)
    //    go process(ch)
    //    for {
    //        time.Sleep(1000 * time.Millisecond)
    //        select {
    //        case v := <-ch:
    //            fmt.Println("received value: ", v)
    //            return
    //        default:
    //            // 可以干其他事,模拟非阻塞式io
    //            fmt.Println("no value received")
    //        }
    //    }
    //
    //}
    
    //死锁
    //func main() {
    //    ch := make(chan string)
    //    select {
    //    case <-ch:
    //    }
    //}
    
    // 随机选取
    func server1(ch chan string) {
        ch <- "from server1"
    }
    func server2(ch chan string) {
        ch <- "from server2"
    
    }
    func main() {
        output1 := make(chan string)
        output2 := make(chan string)
        go server1(output1)
        go server2(output2)
        time.Sleep(1 * time.Second)
        select {
        case s1 := <-output1:
            fmt.Println(s1)
        case s2 := <-output2:
            fmt.Println(s2)
        }
    }
  • 相关阅读:
    Gartner: Hype Cycle for Emerging Technologies-2012 (技术成熟度曲线) [转]
    一个好的软件开发人员必须是一个软件使用的高手[摘]
    十年MFC经历认识的Microsoft技术 [转]
    不同医学成像方法的辐射剂量
    C++100款开源界面库[转]
    【Tool】JDK8 安装
    【Tool】IntelliJ IDEA Ultimate2019.1 中文版 安装
    【性能优化】(2)JVM调优
    【性能优化】(1)概述
    【Design Patterns】(1)概述
  • 原文地址:https://www.cnblogs.com/ZhZhang12138/p/14886772.html
Copyright © 2011-2022 走看看