2021-02-11 11:55:23 +03:00
|
|
|
|
|
|
|
The `sync.pool` module provides a convenient way to run identical tasks over
|
|
|
|
an array of items *in parallel*, without worrying about thread synchronization,
|
|
|
|
waitgroups, mutexes etc.., you just need to supply a callback function, that
|
|
|
|
will be called once per each item in your input array.
|
|
|
|
|
|
|
|
After all the work is done in parallel by the worker threads in the pool,
|
2022-11-26 19:23:26 +03:00
|
|
|
pool.work_on_items will return. You can then call pool.get_results[Result]()
|
2021-02-11 11:55:23 +03:00
|
|
|
to retrieve a list of all the results, that the worker callbacks returned
|
|
|
|
for each input item. Example:
|
|
|
|
|
|
|
|
```v
|
|
|
|
import sync.pool
|
|
|
|
|
2022-09-01 09:22:37 +03:00
|
|
|
pub struct SResult {
|
2021-02-11 11:55:23 +03:00
|
|
|
s string
|
|
|
|
}
|
|
|
|
|
2022-11-10 21:19:19 +03:00
|
|
|
fn sprocess(mut pp pool.PoolProcessor, idx int, wid int) &SResult {
|
2022-11-26 19:23:26 +03:00
|
|
|
item := pp.get_item[string](idx)
|
2022-11-15 16:53:13 +03:00
|
|
|
println('idx: ${idx}, wid: ${wid}, item: ' + item)
|
2021-02-11 11:55:23 +03:00
|
|
|
return &SResult{item.reverse()}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
mut pp := pool.new_pool_processor(callback: sprocess)
|
|
|
|
pp.work_on_items(['1abc', '2abc', '3abc', '4abc', '5abc', '6abc', '7abc'])
|
|
|
|
// optionally, you can iterate over the results too:
|
2022-11-26 19:23:26 +03:00
|
|
|
for x in pp.get_results[SResult]() {
|
2022-11-15 16:53:13 +03:00
|
|
|
println('result: ${x.s}')
|
2021-02-11 11:55:23 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
See https://github.com/vlang/v/blob/master/vlib/sync/pool/pool_test.v for a
|
|
|
|
more detailed usage example.
|