| 1 | import context |
| 2 | import time |
| 3 | import x.async as xasync |
| 4 | |
| 5 | fn main() { |
| 6 | mut pool := xasync.new_pool(workers: 1, queue_size: 1)! |
| 7 | started := chan bool{cap: 2} |
| 8 | release := chan bool{cap: 2} |
| 9 | accepted := chan bool{cap: 1} |
| 10 | ran := chan bool{cap: 1} |
| 11 | context_ran := chan bool{cap: 1} |
| 12 | blocking_job := fn [started, release] (mut ctx context.Context) ! { |
| 13 | _ = ctx |
| 14 | started <- true |
| 15 | _ := <-release |
| 16 | } |
| 17 | |
| 18 | pool.try_submit(blocking_job)! |
| 19 | if !wait_bool(started) { |
| 20 | eprintln('first pool job did not start') |
| 21 | exit(1) |
| 22 | } |
| 23 | pool.try_submit(blocking_job)! |
| 24 | |
| 25 | submitter := spawn fn [mut pool, accepted, ran] () { |
| 26 | pool.submit_with_timeout(1 * time.second, fn [ran] (mut ctx context.Context) ! { |
| 27 | _ = ctx |
| 28 | ran <- true |
| 29 | }) or { |
| 30 | eprintln('bounded submit failed: ${err.msg()}') |
| 31 | accepted <- false |
| 32 | return |
| 33 | } |
| 34 | accepted <- true |
| 35 | }() |
| 36 | |
| 37 | release <- true |
| 38 | if !wait_bool(accepted) { |
| 39 | eprintln('bounded submit was not accepted after capacity opened') |
| 40 | exit(1) |
| 41 | } |
| 42 | |
| 43 | release <- true |
| 44 | if !wait_bool(ran) { |
| 45 | eprintln('bounded submit job did not run') |
| 46 | exit(1) |
| 47 | } |
| 48 | |
| 49 | parent_ctx, cancel := xasync.with_cancel() |
| 50 | defer { |
| 51 | cancel() |
| 52 | } |
| 53 | pool.submit_with_context(parent_ctx, fn [context_ran] (mut ctx context.Context) ! { |
| 54 | _ = ctx |
| 55 | context_ran <- true |
| 56 | })! |
| 57 | if !wait_bool(context_ran) { |
| 58 | eprintln('context-bounded submit job did not run') |
| 59 | exit(1) |
| 60 | } |
| 61 | |
| 62 | pool.close()! |
| 63 | submitter.wait() |
| 64 | println('timeout and context bounded submits completed') |
| 65 | } |
| 66 | |
| 67 | fn wait_bool(ch chan bool) bool { |
| 68 | select { |
| 69 | ok := <-ch { |
| 70 | return ok |
| 71 | } |
| 72 | 1 * time.second { |
| 73 | return false |
| 74 | } |
| 75 | } |
| 76 | return false |
| 77 | } |
| 78 | |