[Golang] Golang Advanced Series Tutorials--What can Go language select do?

foreword

In the Go language, select is a keyword used to monitor IO operations related to channels.

Through the select statement, we can monitor multiple channels at the same time, and perform corresponding processing when any one of the channels is ready.

This article will summarize the common usage of the select statement and the precautions during use.

basic grammar

The basic syntax of the select statement is as follows:

select {
    
    
case <-channel1:
    // 通道 channel1 就绪时的处理逻辑
case data := <-channel2:
    // 通道 channel2 就绪时的处理逻辑
default:
    // 当没有任何通道就绪时的默认处理逻辑
}

Seeing this syntax, it is easy to think of the switch statement.
Although the select statement and the switch statement are superficially similar, their purpose and function are different.
switch is used for conditional judgment, while select is used for channel operation. You cannot use any type of conditional expression in the select statement, only operate on channels.

rules of use

Although the syntax is simple, there are still some points that need to be paid attention to during use. I have summarized the following four points:

The select statement can only be used for channel operations, for selecting between multiple channels, to monitor the ready state of the channel, not for other types of conditional judgments.

The select statement can contain multiple case clauses, and each case clause corresponds to a channel operation. When any one of the channels is ready, the corresponding case clause will be executed.

If multiple channels are ready, the select statement will randomly select a channel to execute. This ensures fair competition among multiple channels.

Execution of select statements may be blocking or non-blocking. If none of the channels are ready and there is no default clause, the select statement will block until a channel is ready. If there is a default clause and no channels are ready, the select statement executes the default clause, avoiding blocking.

multiplexing

One of the most common uses of select is to listen to multiple channels simultaneously and perform different actions based on their readiness.

package main

import (
    "fmt"
    "time"
)

func main() {
    
    
    c1 := make(chan string)
    c2 := make(chan string)

    go func() {
    
    
        time.Sleep(3 * time.Second)
        c1 <- "one"
    }()

    go func() {
    
    
        time.Sleep(3 * time.Second)
        c2 <- "two"
    }()

    select {
    
    
    case msg := <-c1:
        fmt.Println(msg)
    case msg := <-c2:
        fmt.Println(msg)
    }
}

Execute the above code, the program will randomly print one or two, if the channel is empty, the program will always be blocked there.

non-blocking communication

Ordinary read and write operations will block when there is no data to read or no buffer space to write in the channel.
But through the select statement, we can execute the default logic when there is no data ready, so as to avoid the program from falling into an infinite waiting state.

package main

import (
    "fmt"
)

func main() {
    
    
    channel := make(chan int)

    select {
    
    
    case data := <-channel:
        fmt.Println("Received:", data)
    default:
        fmt.Println("No data available.")
    }
}

Execute the above code, the program will execute the default branch.
output:

No data available.

Timeout processing

By combining the select and time.After functions, we can wait for the channel to be ready within a specified time, and execute the corresponding logic after the time exceeds.

package main

import (
    "fmt"
    "time"
)

func main() {
    
    
    channel := make(chan int)

    select {
    
    
    case data := <-channel:
        fmt.Println("Received:", data)
    case <-time.After(3 * time.Second):
        fmt.Println("Timeout occurred.")
    }
}

Execute the above code, if the channel has no data to read within 3 seconds, select will execute the time.After branch.
output:

Timeout occurred.

The above is the whole content of this article. If you think it is not bad, please like, repost and follow. Thank you for your support.

Guess you like

Origin blog.csdn.net/u011397981/article/details/132044361