Home > OS >  about the key ”defer”and “select” in Go
about the key ”defer”and “select” in Go

Time:11-10

func TestContext(t *testing.T){
    message:=make(chan int,10)
    //producer
    for i:=0;i<10;i  {
        message<-i
    }
    
    //consumer
    ctx,cancel:=context.WithTimeout(context.Background(),time.Second*5)

    go func(ctx context.Context) {
            ticker := time.NewTicker(1 * time.Second)
            for _ = range ticker.C { 
                select {
                case <-ctx.Done():
                    fmt.Println("child process interrupt...")
                    return
                default:
                    fmt.Printf("send message: %d\n", <-message)
                }
            }
        }(ctx)
    
    defer close(message)
    defer cancel()
    select{
        case <-ctx.Done():
            //time.Sleep(1*time.Second)
            fmt.Println("main process exit!")
    }

}

Q1: when is the “defer cancel” executed? after select ?

Q2: In Q1,if "defer cancel" is executed after select , will the ctx.Done() return nil? and will the select be blocked?

CodePudding user response:

All deferred function calls will run after the function body runs, but before the function returns, so yes, defer cancel will execute after select.

Select will block until the context times out. When the context times out, the <-ctx.Done() case will be enabled, so select can continue after the context timeout.

  •  Tags:  
  • go
  • Related