futures.scm 11 KB

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