chickadee » srfi-18 » thread-join!

thread-join! thread #!optional timeout timeout-valprocedure

The current thread waits until the thread terminates (normally or not) or until the timeout is reached if timeout is supplied. If the timeout is reached, thread-join! returns timeout-val if it is supplied, otherwise a "join timeout exception" is raised. If the thread terminated normally, the content of the end-result field is returned, otherwise the content of the end-exception field is raised.

    (let ((t (thread-start! (make-thread (lambda () (expt 2 100))))))
      (do-something-else)
      (thread-join! t))  ==>  1267650600228229401496703205376
 
    (let ((t (thread-start! (make-thread (lambda () (raise 123))))))
      (do-something-else)
      (with-exception-handler
        (lambda (exc)
          (if (uncaught-exception? exc)
              (* 10 (uncaught-exception-reason exc))
              99999))
        (lambda ()
          (+ 1 (thread-join! t)))))  ==>  1231
 
    (define thread-alive?
      (let ((unique (list 'unique)))
        (lambda (thread)
          ; Note: this procedure raises an exception if
          ; the thread terminated abnormally.
          (eq? (thread-join! thread 0 unique) unique))))
 
    (define (wait-for-termination! thread)
      (let ((eh (current-exception-handler)))
        (with-exception-handler
          (lambda (exc)
            (if (not (or (terminated-thread-exception? exc)
                         (uncaught-exception? exc)))
                (eh exc))) ; unexpected exceptions are handled by eh
          (lambda ()
            ; The following call to thread-join! will wait until the
            ; thread terminates.  If the thread terminated normally
            ; thread-join! will return normally.  If the thread
            ; terminated abnormally then one of these two exceptions
            ; is raised by thread-join!:
            ;   - terminated thread exception
            ;   - uncaught exception
            (thread-join! thread)
            #f)))) ; ignore result of thread-join!