選択したキーワードを行きます

選択

この関数は非ブロックモードを実装するために使用されるキーワードは、一般的に移動中の言語を使用している選択し、Linuxは早くも導入することができ、select文は、送信を選択するか、すぐに実行することができる場合の動作を受信するために使用されます。これは、switch文に似ていますが、I / O操作をチャンネルに関連する場合です。

select{
case <-chan1:
    // 如果成功读取到chan1中得数据,则进行该case处理语句
case chan2 <- value:
    // 如果成功像chan2中写入数据,则进行该case处理语句
default:
    // 如果上面都没有成功,则进入default处理语句
}

シンプルなケース:

func main(){
    ch := make(chan int)
    go func(){
        ch <- 10
    }()
    time.Sleep(time.Second)
    
    select{
    case <- ch:
        fmt.Println("come to read channel")
    default:
        fmt.Println("come to default")
    }
}

タイムアウト制御

例すべてが成功していない、とデフォルトの文が存在しない場合は、ステートメントを選択するブロックされていたであろう、少なくとも1つのI / O操作を知っているが、ブロックされていたであろうでない場合は、次に我々は、タイムアウト制御を設定することができます。

この方法は、コルーチンを使用して実装しました。

func main(){
    timeout := make(chan bool)
    ch := make(chan string)
    
    go func(ch chan bool){
        time.Sleep(time.Second * 2)
        ch <- true
    }(timeout)
    
    select {
    case value := <-ch:
        fmt.Printf("value is %v",value)
    case <= timeout: 
        fmt.Println("runing timeout...")
    }
    fmt.Println("end this demo")
}

出力:

runing timeout...
end this demo

time.After()メソッドの実装を使用して、2つの実装。

func main(){
    ch := make(chan string)
    
    select {
    case value := <-ch:
        fmt.Printf("value is %v",value)
    case <= time.After(time.Second): 
        fmt.Println("runing timeout...")
    }
    fmt.Println("end this demo")
}

出力:

runing timeout...
end this demo

ブレークキーワードの終わりには、選択します

ケース:

func main(){
    ch1 := make(chan int,1)
    ch2 := make(chan int,1)
    
    select{
    case ch1 <- 10:
        fmt.Println("this is ch1")
        break
        fmt.Println("ch1 write value")
    case ch2 <-20:
        fmt.Println("this is ch2")
        fmt.Println("ch2 write value")
    }
}

最初のケースのCH1が検出を実行することを選択したときに上記のコード、CH1とCH2の両方の値を書き込むことができますチャンネルは、システムがランダムにだけでなく、原因、それは一つだけを印刷します破るキーワードが存在するために、ケースの実行を選択します:

this is ch1

しかし、CH2ケースの実装は、すべてのコンテンツが印刷されます。

this is ch2
ch2 write value

おすすめ

転載: www.cnblogs.com/louyefeng/p/11368537.html