v / vlib / context
Raw file | 50 loc (44 sloc) | 1.29 KB | Latest commit hash 4490d5ed2
1import context
2import time
3
4const (
5 // a reasonable duration to block in an example
6 short_duration = 1 * time.millisecond
7)
8
9// This example passes a context with an arbitrary deadline to tell a blocking
10// function that it should abandon its work as soon as it gets to it.
11fn test_with_deadline() {
12 dur := time.now().add(short_duration)
13 mut background := context.background()
14 mut ctx, cancel := context.with_deadline(mut background, dur)
15
16 defer {
17 // Even though ctx will be expired, it is good practice to call its
18 // cancellation function in any case. Failure to do so may keep the
19 // context and its parent alive longer than necessary.
20 cancel()
21 }
22
23 ctx_ch := ctx.done()
24 select {
25 _ := <-ctx_ch {}
26 1 * time.second {
27 panic('This should not happen')
28 }
29 }
30}
31
32// This example passes a context with a timeout to tell a blocking function that
33// it should abandon its work after the timeout elapses.
34fn test_with_timeout() {
35 // Pass a context with a timeout to tell a blocking function that it
36 // should abandon its work after the timeout elapses.
37 mut background := context.background()
38 mut ctx, cancel := context.with_timeout(mut background, short_duration)
39 defer {
40 cancel()
41 }
42
43 ctx_ch := ctx.done()
44 select {
45 _ := <-ctx_ch {}
46 1 * time.second {
47 panic('This should not happen')
48 }
49 }
50}