Created
January 14, 2022 11:07
-
-
Save kougazhang/a32878bb09c7eed503d2623b951bc6ea to your computer and use it in GitHub Desktop.
#golang #context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"time" | |
) | |
const shortDuration = time.Millisecond | |
func main() { | |
d := time.Now().Add(shortDuration) | |
ctx, cancel := context.WithDeadline(context.Background(), d) | |
// 即便 ctx 会过期,为了以防万一调用 cancellation 函数也是一个好习惯 | |
// 失败可能会导致 ctx 不过期,这样的话 parent 会比预期时存活更长 | |
defer cancel() | |
select { | |
case <-time.After(time.Second): | |
fmt.Println("overslept") | |
case <-ctx.Done(): | |
fmt.Println(ctx.Err()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment