Why do we need to wait for select in Go?

王林
Release: 2024-02-11 08:24:09
forward
1203 people have browsed it

Why do we need to wait for select in Go?

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.

Question content

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)
    }
  }
}
Copy after login

Want to ask

Why does this happen. What knowledge do I need?

I'm expecting the output.

But the actual output obtained does not contain "termination".

value1
value2
pre cancel
terminate
post cancel
Copy after login

Fixed code

I added time.Sleep under the cancel function. Then the output is what I expected.

ctxCancel()
time.Sleep(100 * time.Millisecond) // add
Copy after login

Solution

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")
    }
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template