select is a commonly used keyword in the Go language. It is used to monitor IO operations related to channels. When an IO operation occurs, the corresponding action is triggered.
If there are multiple cases that can be run, Select will randomly and fairly select one for execution. Others will not be executed. (Recommended learning: go)
Otherwise:
If there is a default clause, the statement will be executed.
Without the default clause, select will block until a communication can run; Go will not re-evaluate the channel or value.
Basic usage
//select基本用法 select { case <- chan1: // 如果chan1成功读到数据,则进行该case处理语句 case chan2 <- 1: // 如果成功向chan2写入数据,则进行该case处理语句 default: // 如果上面都没有成功,则进入default处理流程
If one or more IO operations can be completed, the Go runtime system will randomly select one for execution, otherwise, If there is a default branch, the default branch statement is executed. If there is no default, the select statement will block until at least one IO operation can be performed.
start := time.Now() c := make(chan interface{}) ch1 := make(chan int) ch2 := make(chan int) go func() { time.Sleep(4*time.Second) close(c) }() go func() { time.Sleep(3*time.Second) ch1 <- 3 }() go func() { time.Sleep(3*time.Second) ch2 <- 5 }() fmt.Println("Blocking on read...") select { case <- c: fmt.Printf("Unblocked %v later.\n", time.Since(start)) case <- ch1: fmt.Printf("ch1 case...") case <- ch2: fmt.Printf("ch1 case...") default: fmt.Printf("default go...") }
Run the above code. Since the current time is still Less than 3 seconds. Therefore, the current program will run by default.
The above is the detailed content of Does golang select not block?. For more information, please follow other related articles on the PHP Chinese website!