Jim Newton
7/3/2015 1:44:00 PM
Can someone give tell me how to start a list of threads in sbcl, and wait until they've finished?
For example:
(let ((running (mapcar (lambda (n)
(sb-thread:make-thread
(lambda ()
(format t "n = ~A~%" n)
(finish-output))))
'(1 2 3 4))))
(wait-until-finished running))
If I know in advance how many threads I'm going to start, I could set up some sort of counter, like the following. But there must be an easier way, especially in the case that I don't know before hand how many threads I wish to start.
Besides this implementation has the disadvantage that the "all finished" message is printed in the last thread to finish, not in the main thread where I want it.
(defun 12-threads ()
(let ((max-how-many 12)
(how-many 0)
(mutex (sb-thread:make-mutex)))
(flet ((finished? ()
(sb-thread:with-mutex (mutex)
(incf how-many)
(eql how-many max-how-many))))
(dotimes (n max-how-many)
(let ((n n))
(sb-thread:make-thread
(lambda ()
;; do some work
(format t "n = ~A~%" n)
(when (finished?)
(format t "all finished~%")))))))))