php editor Zimo introduced: In the Go language, the select statement is a very important control flow statement. It is used to monitor the operations of multiple channels at the same time to achieve concurrency control. . Why do you need to wait for selection? This is because in concurrent programming, we usually need to process data or events from multiple channels at the same time, and the select statement can help us monitor multiple channels. Once any one of the channels is operable, the corresponding operation will be performed, thereby achieving concurrency. deal with. By using select, we can effectively avoid blocking and improve the responsiveness and concurrency of the program.
I just learned about context cancellation. Here is my code.
package main import ( "fmt" "context" ) func main() { ctx := context.Background() do(ctx) } func do(ctx context.Context) { ctx, ctxCancel := context.WithCancel(ctx) resultCh := make(chan string) go terminate(ctx, resultCh) resultCh <- "value1" resultCh <- "value2" fmt.Println("pre cancel") ctxCancel() fmt.Println("post cancel") } func terminate(ctx context.Context, ch <-chan string) { for { select { case <-ctx.Done(): fmt.Println("terminate") return case result := <-ch: fmt.Println(result) } } }
Why does this happen. What knowledge do I need?
But the actual output obtained does not contain "termination".
value1 value2 pre cancel terminate post cancel
I added time.Sleep under the cancel function. Then the output is what I expected.
ctxCancel() time.Sleep(100 * time.Millisecond) // add
As I understand it, the core idea behind using select is to wait for at least one condition to be "ready". I've provided an example below that might help. Here select is used to wait for a value to be received from channel ch or for a 1 second timeout to occur.
import ( "fmt" "time" ) func main() { ch := make(chan int) go func() { // Simulate some time-consuming operation time.Sleep(2 * time.Second) ch <- 42 }() select { case result := <-ch: fmt.Println("Received result:", result) case <-time.After(1 * time.Second): fmt.Println("Timeout reached") } }
The above is the detailed content of Why do we need to wait for select in Go?. For more information, please follow other related articles on the PHP Chinese website!