Skip to content

Instantly share code, notes, and snippets.

@orthecreedence
Last active August 29, 2015 14:02
Show Gist options
  • Save orthecreedence/10779bc083d915d19b04 to your computer and use it in GitHub Desktop.
Save orthecreedence/10779bc083d915d19b04 to your computer and use it in GitHub Desktop.
(defun return-fastest (&rest functions)
(let* ((retvals nil)
(threads nil)
(results-lock (bt:make-lock "results"))
(sig (bt:make-condition-variable))
(wrapped (mapcar (lambda (fn)
(lambda ()
(let ((got-results (bt:with-lock-held (results-lock) retvals)))
(format t "th: res1: ~a~%" got-results)
(unless got-results
(let ((local-vals (multiple-value-list (funcall fn))))
(format t "th: comp: ~a~%" local-vals)
(bt:with-lock-held (results-lock)
(format t "th: res2: ~a~%" local-vals)
(unless retvals
(setf retvals local-vals)
(format t "th: setting res, firing sig ~a~%" sig)
(bt:condition-notify sig)
(format t "th: sig fired~%"))))))))
functions)))
(dolist (fn wrapped)
(format t "starting thread~%")
(push (bt:make-thread fn) threads))
(bt:with-lock-held (results-lock)
(unless retvals
(format t "waiting on sig ~a~%" sig)
(bt:condition-wait sig results-lock)))
(values-list retvals)))
(format t "~%starting...~%")
(let ((res (return-fastest
(lambda () (sleep 2) (+ 4 5))
(lambda () (+ 27 84))
(lambda () (+ 45 23)))))
(format t "res: ~a~%" res))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment