parallelism.scm 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. (define-module (parallelism)
  2. #:export (run-in-parallel))
  3. (use-modules
  4. ;; for parallel forms
  5. (ice-9 threads)
  6. ;; for futures
  7. (ice-9 futures)
  8. ;; srfi 8 for receive form
  9. (srfi srfi-8))
  10. #|
  11. ;; This has to be a macro, because ~parallel~ takes simple expressions instead
  12. ;; of lambdas to run. Such expressions would be evaluated as arguments, before
  13. ;; ~using-parallel-forms~ would be called with the results. ~parallel~ itself is
  14. ;; a macro, which is why it can take raw expressions instead of making the user
  15. ;; wrap expressions in lambdas.
  16. (define-syntax run-in-parallel-forms
  17. (syntax-rules ()
  18. [(_ expr ...)
  19. (parallel expr ...)]))
  20. |#
  21. (define map-future
  22. (lambda (proc data)
  23. (map (lambda (data-part)
  24. (future (proc data-part)))
  25. data)
  26. ;; (let future-iter ([args data] [futures '()])
  27. ;; (cond
  28. ;; [(null? args) futures]
  29. ;; [else
  30. ;; (future-iter (cdr args)
  31. ;; (cons (future (proc (car args)))
  32. ;; futures))]))
  33. ))
  34. (define map-touch
  35. (lambda (futures)
  36. (map (lambda (a-future)
  37. (touch a-future))
  38. futures)))
  39. ;; ~run-in-parallel~ is the piece of code, which you should adapt, if you want
  40. ;; to use something else than parallel forms.
  41. (define-public run-in-parallel
  42. (lambda (proc data)
  43. "Apply proc to all elements in data in parallel."
  44. ;; Create futures and then touch the list of created futures. Return the
  45. ;; results of the futures.
  46. ;; (display (simple-format #f "Running ~a in parallel over ~a.\n" proc data))
  47. (display (simple-format #f "Running ~a in parallel.\n" proc))
  48. (map-touch
  49. (map-future proc data))))
  50. ;; Below example procedures for busy work are defined.
  51. #;(define busy-work
  52. (lambda ()
  53. (let loop ([i 0])
  54. (cond
  55. [(< i 2e8) (loop (+ i 1))]
  56. [else i]))))
  57. ;; (run-in-parallel (lambda (_) (busy-work))
  58. ;; '(1 2 3 4))
  59. #;(run-in-parallel
  60. (busy-work)
  61. (busy-work)
  62. (busy-work)
  63. (busy-work))