We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
正常执行代码示例
package main import ( "context" "fmt" "time" ) func main() { ctx := context.Background() timeout := time.Second*2 ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() done := make(chan int, 1) // do work go func() { fmt.Println("do working") time.Sleep(time.Second) // work done done <- 1 }() select { case <-ctx.Done(): fmt.Println(ctx.Err()) case <-done: fmt.Println("work done on time") } fmt.Println("main func exit") }
输出结果
do working work done on time main func exit
超时示例
package main import ( "context" "fmt" "time" ) func main() { ctx := context.Background() timeout := time.Second*2 ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() done := make(chan int, 1) // do work go func() { fmt.Println("do working") //time.Sleep(time.Second) // 超时 time.Sleep(time.Second*3) // work done done <- 1 }() // 阻塞,等待 select { // 统一超时处理 case <-ctx.Done(): fmt.Println(ctx.Err()) case <-done: fmt.Println("work done on time") } fmt.Println("main func exit") }
执行结果
do working context deadline exceeded main func exit
The text was updated successfully, but these errors were encountered:
No branches or pull requests
正常执行代码示例
输出结果
超时示例
执行结果
The text was updated successfully, but these errors were encountered: