v2 / vlib / x / async / examples / worker_pool.v
45 lines · 39 sloc · 786 bytes · 15fb60b77ea6073658aa8355b247f2e1ae03b714
Raw
1import context
2import time
3import x.async as xasync
4
5fn main() {
6 mut pool := xasync.new_pool(workers: 1, queue_size: 1)!
7 started := chan int{cap: 2}
8 release := chan bool{cap: 2}
9 job := fn [started, release] (mut ctx context.Context) ! {
10 _ = ctx
11 started <- 1
12 _ := <-release
13 }
14
15 pool.try_submit(job)!
16 if !wait_started(started) {
17 eprintln('pool job did not start')
18 exit(1)
19 }
20
21 pool.try_submit(job)!
22 pool.try_submit(job) or { println('backpressure: ${err.msg()}') }
23
24 release <- true
25 if !wait_started(started) {
26 eprintln('pool job did not start')
27 exit(1)
28 }
29 release <- true
30
31 pool.close()!
32 println('pool drained')
33}
34
35fn wait_started(started chan int) bool {
36 select {
37 _ := <-started {
38 return true
39 }
40 1 * time.second {
41 return false
42 }
43 }
44 return false
45}
46