Course of Raku / Functional, concurrent, reactive, and web programming / Concurrent programming / Hyper and race 🆕
Parallel maps with hyper
Call .hyper on a list before a map or
grep, and the work is spread across multiple worker threads
— while the results still come back in the original
order:
say (1..5).hyper.map(* * 2); # (2 4 6 8 10)This looks exactly like an ordinary map, and the result
is identical; the only difference is that the doublings may have been
computed on different cores at the same time. Because
.hyper preserves order, you can use it as a drop-in
replacement for a slow map without changing anything that
depends on the order of the results:
say (1..10).hyper.grep(* %% 2); # (2 4 6 8 10)The benefit only appears when each element’s work is large enough to
outweigh the cost of coordinating threads — squaring a number is far too
cheap to be worth parallelising in reality. For genuinely expensive
per-element work over a big list, .hyper can turn a long
wait into a short one for the price of a single method call.
Order is preserved, so reductions work as expected too:
say (1..100).hyper.map(* * 2).sum; # 10100Practice
Complete the quiz that covers the contents of this topic.
Course navigation
← Hyper and race 🆕 | Quiz — hyper →
💪 Or jump directly to the exercises in this
section.