parallelism.scm 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. (library (parallelism)
  2. (export run-in-parallel)
  3. (import
  4. (except (rnrs base) let-values map)
  5. (only (guile)
  6. lambda* λ)
  7. (ice-9 futures)
  8. (srfi srfi-1))
  9. (define run-in-parallel
  10. (λ (segments map-proc reduce-proc reduce-init)
  11. "Use futures to run a procedure in parallel, if
  12. multiple cores are available. Take a list of SEGMENTS as
  13. input, which are ranges of values to work on. MAP-PROC is
  14. applied to the SEGMENTS using map. When the MAP-PROC calls
  15. for all segments finished and returned values, the
  16. REDUCE-PROC is applied to the map result using reduce and
  17. the REDUCE-INIT argument."
  18. (let ([futures
  19. (map (λ (seg)
  20. (make-future
  21. ;; Need to wrap in a thunk, to not
  22. ;; immediately start evaluating.
  23. (λ () (map-proc seg))))
  24. segments)])
  25. (let ([segment-results (map touch futures)])
  26. (reduce reduce-proc
  27. reduce-init
  28. segment-results))))))