1 | import context |
2 | import time |
3 | |
4 | const ( |
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. |
11 | fn 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. |
34 | fn 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 | } |