futures.scm 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. ;;; -*- mode: scheme; coding: utf-8; -*-
  2. ;;;
  3. ;;; Copyright (C) 2010, 2011, 2012 Free Software Foundation, Inc.
  4. ;;;
  5. ;;; This library is free software; you can redistribute it and/or
  6. ;;; modify it under the terms of the GNU Lesser General Public
  7. ;;; License as published by the Free Software Foundation; either
  8. ;;; version 3 of the License, or (at your option) any later version.
  9. ;;;
  10. ;;; This library is distributed in the hope that it will be useful,
  11. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. ;;; Lesser General Public License for more details.
  14. ;;;
  15. ;;; You should have received a copy of the GNU Lesser General Public
  16. ;;; License along with this library; if not, write to the Free Software
  17. ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  18. (define-module (ice-9 futures)
  19. #:use-module (srfi srfi-1)
  20. #:use-module (srfi srfi-9)
  21. #:use-module (srfi srfi-9 gnu)
  22. #:use-module (srfi srfi-11)
  23. #:use-module (ice-9 q)
  24. #:use-module (ice-9 match)
  25. #:use-module (ice-9 control)
  26. #:use-module (ice-9 threads)
  27. #:export (future make-future future? touch))
  28. ;;; Author: Ludovic Courtès <ludo@gnu.org>
  29. ;;;
  30. ;;; Commentary:
  31. ;;;
  32. ;;; This module provides an implementation of futures, a mechanism for
  33. ;;; fine-grain parallelism. Futures were first described by Henry Baker
  34. ;;; in ``The Incremental Garbage Collection of Processes'', 1977, and
  35. ;;; then implemented in MultiLisp (an implicit variant thereof, i.e.,
  36. ;;; without `touch'.)
  37. ;;;
  38. ;;; This modules uses a fixed thread pool, normally one per CPU core.
  39. ;;; Futures are off-loaded to these threads, when they are idle.
  40. ;;;
  41. ;;; Code:
  42. ;;;
  43. ;;; Futures.
  44. ;;;
  45. (define-record-type <future>
  46. (%make-future thunk state mutex completion)
  47. future?
  48. (thunk future-thunk set-future-thunk!)
  49. (state future-state set-future-state!) ; done | started | queued
  50. (result future-result set-future-result!)
  51. (mutex future-mutex)
  52. (completion future-completion)) ; completion cond. var.
  53. (set-record-type-printer!
  54. <future>
  55. (lambda (future port)
  56. (simple-format port "#<future ~a ~a ~s>"
  57. (number->string (object-address future) 16)
  58. (future-state future)
  59. (future-thunk future))))
  60. (define (make-future thunk)
  61. "Return a new future for THUNK. Execution may start at any point
  62. concurrently, or it can start at the time when the returned future is
  63. touched."
  64. (create-workers!)
  65. (let ((future (%make-future thunk 'queued
  66. (make-mutex) (make-condition-variable))))
  67. (register-future! future)
  68. future))
  69. ;;;
  70. ;;; Future queues.
  71. ;;;
  72. ;; Global queue of pending futures.
  73. ;; TODO: Use per-worker queues to reduce contention.
  74. (define %futures (make-q))
  75. ;; Lock for %FUTURES and %FUTURES-WAITING.
  76. (define %futures-mutex (make-mutex))
  77. (define %futures-available (make-condition-variable))
  78. ;; A mapping of nested futures to futures waiting for them to complete.
  79. (define %futures-waiting '())
  80. ;; Whether currently running within a future.
  81. (define %within-future? (make-parameter #f))
  82. (define-syntax-rule (with-mutex m e0 e1 ...)
  83. ;; Copied from (ice-9 threads) to avoid circular dependency.
  84. (let ((x m))
  85. (dynamic-wind
  86. (lambda () (lock-mutex x))
  87. (lambda () (begin e0 e1 ...))
  88. (lambda () (unlock-mutex x)))))
  89. (define %future-prompt
  90. ;; The prompt futures abort to when they want to wait for another
  91. ;; future.
  92. (make-prompt-tag))
  93. (define (register-future! future)
  94. ;; Register FUTURE as being processable.
  95. (lock-mutex %futures-mutex)
  96. (enq! %futures future)
  97. (signal-condition-variable %futures-available)
  98. (unlock-mutex %futures-mutex))
  99. (define (process-future! future)
  100. "Process FUTURE. When FUTURE completes, return #t and update its
  101. result; otherwise, when FUTURE touches a nested future that has not
  102. completed yet, then suspend it and return #f. Suspending a future
  103. consists in capturing its continuation, marking it as `queued', and
  104. adding it to the waiter queue."
  105. (let/ec return
  106. (let* ((suspend
  107. (lambda (cont future-to-wait)
  108. ;; FUTURE wishes to wait for the completion of FUTURE-TO-WAIT.
  109. ;; At this point, FUTURE is unlocked and in `started' state,
  110. ;; and FUTURE-TO-WAIT is unlocked.
  111. (with-mutex %futures-mutex
  112. (with-mutex (future-mutex future)
  113. (set-future-thunk! future cont)
  114. (set-future-state! future 'queued))
  115. (with-mutex (future-mutex future-to-wait)
  116. ;; If FUTURE-TO-WAIT completed in the meantime, then
  117. ;; reschedule FUTURE directly; otherwise, add it to the
  118. ;; waiter queue.
  119. (if (eq? 'done (future-state future-to-wait))
  120. (begin
  121. (enq! %futures future)
  122. (signal-condition-variable %futures-available))
  123. (set! %futures-waiting
  124. (alist-cons future-to-wait future
  125. %futures-waiting))))
  126. (return #f))))
  127. (thunk (lambda ()
  128. (call-with-prompt %future-prompt
  129. (lambda ()
  130. (parameterize ((%within-future? #t))
  131. ((future-thunk future))))
  132. suspend))))
  133. (set-future-result! future
  134. (catch #t
  135. (lambda ()
  136. (call-with-values thunk
  137. (lambda results
  138. (lambda ()
  139. (apply values results)))))
  140. (lambda args
  141. (lambda ()
  142. (apply throw args)))))
  143. #t)))
  144. (define (process-one-future)
  145. "Attempt to pick one future from the queue and process it."
  146. ;; %FUTURES-MUTEX must be locked on entry, and is locked on exit.
  147. (or (q-empty? %futures)
  148. (let ((future (deq! %futures)))
  149. (lock-mutex (future-mutex future))
  150. (case (future-state future)
  151. ((done started)
  152. ;; Nothing to do.
  153. (unlock-mutex (future-mutex future)))
  154. (else
  155. ;; Do the actual work.
  156. ;; We want to release %FUTURES-MUTEX so that other workers can
  157. ;; progress. However, to avoid deadlocks, we have to unlock
  158. ;; FUTURE as well, to preserve lock ordering.
  159. (unlock-mutex (future-mutex future))
  160. (unlock-mutex %futures-mutex)
  161. (lock-mutex (future-mutex future))
  162. (if (eq? (future-state future) 'queued) ; lost the race?
  163. (begin ; no, so let's process it
  164. (set-future-state! future 'started)
  165. (unlock-mutex (future-mutex future))
  166. (let ((done? (process-future! future)))
  167. (when done?
  168. (with-mutex %futures-mutex
  169. (with-mutex (future-mutex future)
  170. (set-future-state! future 'done)
  171. (notify-completion future))))))
  172. (unlock-mutex (future-mutex future))) ; yes
  173. (lock-mutex %futures-mutex))))))
  174. (define (process-futures)
  175. "Continuously process futures from the queue."
  176. (lock-mutex %futures-mutex)
  177. (let loop ()
  178. (when (q-empty? %futures)
  179. (wait-condition-variable %futures-available
  180. %futures-mutex))
  181. (process-one-future)
  182. (loop)))
  183. (define (notify-completion future)
  184. "Notify futures and callers waiting that FUTURE completed."
  185. ;; FUTURE and %FUTURES-MUTEX are locked.
  186. (broadcast-condition-variable (future-completion future))
  187. (let-values (((waiting remaining)
  188. (partition (match-lambda ; TODO: optimize
  189. ((waitee . _)
  190. (eq? waitee future)))
  191. %futures-waiting)))
  192. (set! %futures-waiting remaining)
  193. (for-each (match-lambda
  194. ((_ . waiter)
  195. (enq! %futures waiter)))
  196. waiting)))
  197. (define (touch future)
  198. "Return the result of FUTURE, computing it if not already done."
  199. (define (work)
  200. ;; Do some work while waiting for FUTURE to complete.
  201. (lock-mutex %futures-mutex)
  202. (if (q-empty? %futures)
  203. (begin
  204. (unlock-mutex %futures-mutex)
  205. (with-mutex (future-mutex future)
  206. (unless (eq? 'done (future-state future))
  207. (wait-condition-variable (future-completion future)
  208. (future-mutex future)))))
  209. (begin
  210. (process-one-future)
  211. (unlock-mutex %futures-mutex))))
  212. (let loop ()
  213. (lock-mutex (future-mutex future))
  214. (case (future-state future)
  215. ((done)
  216. (unlock-mutex (future-mutex future)))
  217. ((started)
  218. (unlock-mutex (future-mutex future))
  219. (if (%within-future?)
  220. (abort-to-prompt %future-prompt future)
  221. (begin
  222. (work)
  223. (loop))))
  224. (else
  225. (unlock-mutex (future-mutex future))
  226. (work)
  227. (loop))))
  228. ((future-result future)))
  229. ;;;
  230. ;;; Workers.
  231. ;;;
  232. (define %worker-count
  233. (if (provided? 'threads)
  234. (- (current-processor-count) 1)
  235. 0))
  236. ;; A dock of workers that stay here forever.
  237. ;; TODO
  238. ;; 1. Allow the pool to be shrunk, as in libgomp (though that we'd
  239. ;; need semaphores, which aren't yet in libguile!).
  240. ;; 2. Provide a `worker-count' fluid.
  241. (define %workers '())
  242. (define (%create-workers!)
  243. (with-mutex
  244. %futures-mutex
  245. ;; Setting 'create-workers!' to a no-op is an optimization, but it is
  246. ;; still possible for '%create-workers!' to be called more than once
  247. ;; from different threads. Therefore, to avoid creating %workers more
  248. ;; than once (and thus creating too many threads), we check to make
  249. ;; sure %workers is empty within the critical section.
  250. (when (null? %workers)
  251. (set! %workers
  252. (unfold (lambda (i) (>= i %worker-count))
  253. (lambda (i) (call-with-new-thread process-futures))
  254. 1+
  255. 0))
  256. (set! create-workers! (lambda () #t)))))
  257. (define create-workers!
  258. (lambda () (%create-workers!)))
  259. ;;;
  260. ;;; Syntax.
  261. ;;;
  262. (define-syntax-rule (future body)
  263. "Return a new future for BODY."
  264. (make-future (lambda () body)))
  265. ;;; Local Variables:
  266. ;;; eval: (put 'with-mutex 'scheme-indent-function 1)
  267. ;;; End: