| 1 | // This example illustrates how to use `sync.pool`, |
| 2 | // and how the various settings for VJOBS, work items etc can interact. |
| 3 | @[has_globals] |
| 4 | module main |
| 5 | |
| 6 | import log |
| 7 | import time |
| 8 | import runtime |
| 9 | import sync.pool |
| 10 | |
| 11 | const args = arguments() |
| 12 | const nitems = args[1] or { '10' }.int() |
| 13 | const njobs = args[2] or { runtime.nr_jobs().str() }.int() |
| 14 | const delay = args[3] or { '1000' }.int() |
| 15 | |
| 16 | __global msgs = chan string{cap: 1000} |
| 17 | |
| 18 | fn worker_sleep(mut p pool.PoolProcessor, item_idx int, worker_id int) voidptr { |
| 19 | item := p.get_item[int](item_idx) |
| 20 | msgs <- '# worker_id: ${worker_id:3}, item_idx: ${item_idx + 1:03}, item: ${item:6}, started' |
| 21 | time.sleep(delay * time.millisecond) |
| 22 | msgs <- '# worker_id: ${worker_id:3}, item_idx: ${item_idx + 1:03}, item: ${item:6}, finished.' |
| 23 | return pool.no_result |
| 24 | } |
| 25 | |
| 26 | fn logger() { |
| 27 | for { |
| 28 | msg := <-msgs |
| 29 | log.info(msg) |
| 30 | if msg == '>>> done' { |
| 31 | break |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | fn main() { |
| 37 | t := spawn logger() |
| 38 | msgs <- '>>> nitems: ${nitems:6} | njobs: ${njobs:6} | delay_ms: ${delay:6}' |
| 39 | items := []int{len: nitems, init: index * 1000} |
| 40 | mut fetcher_pool := pool.new_pool_processor(callback: worker_sleep) |
| 41 | fetcher_pool.work_on_items(items) |
| 42 | msgs <- '>>> done' |
| 43 | t.wait() |
| 44 | } |
| 45 | |