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