Go Select keywords

select

select a keyword is commonly used language in Go, Linux could be introduced as early as this function is used to implement a non-blocking mode, a select statement is used to select transmit or receive operation which case can be executed immediately. It is similar to the switch statement, but it relates to the case relating to channel I / O operation.

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

Simple Case:

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")
    }
}

Timeout control

If all of the case have not been successful, and there is no default statement, select the statement would have been blocked, know at least one I / O operation, but if not, would have been blocked, then we can set a timeout control.

A method implemented using a coroutine:

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")
}

Output:

runing timeout...
end this demo

Two implementations using time.After () method implementation:

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")
}

Output:

runing timeout...
end this demo

The end of the break keyword select

Case:

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")
    }
}

The code above, ch1 and ch2 both channels can write values, the system will randomly select a case execution, when the first case ch1 choose to perform discovery, but also due to the presence of keywords break, it will only print one:

this is ch1

However, the implementation of ch2 case, all content will be printed:

this is ch2
ch2 write value

Guess you like

Origin www.cnblogs.com/louyefeng/p/11368537.html