This commit is contained in:
Justin Ethier 2016-02-19 19:41:22 -05:00
parent 3aad258a76
commit f432900cb7
2 changed files with 28 additions and 3 deletions

View file

@ -1,4 +1,4 @@
;;;; A simple example of using a condition variable to simulate thread-join
;;;; An example of using condition variable broadcast to wake other threads.
(import (scheme base)
(scheme read)
(scheme write)
@ -7,14 +7,16 @@
(define cv (make-condition-variable))
(define m (make-mutex))
;; Thread - Sleep, then wake other threads up via broadcast
(thread-start!
(make-thread
(lambda ()
(write "started thread")
(thread-sleep! 5000)
(thread-sleep! 3000)
(condition-variable-broadcast! cv)
(write "thread done"))))
;; Thread - wait for broadcast
(thread-start!
(make-thread
(lambda ()
@ -22,9 +24,9 @@
(mutex-lock! m)
(write "register waiting thread cv")
(mutex-unlock! m cv)
;; TODO: think this is never printed because mutex is locked after waking up..
(write "waiting thread done"))))
;; Main thread - wait for broadcast
(mutex-lock! m)
(mutex-unlock! m cv) ;; Wait on cv
(write "main thread done")

View file

@ -0,0 +1,23 @@
;;;; A simple example of using a condition variable to simulate thread-join
(import (scheme base)
(scheme read)
(scheme write)
(srfi 18))
(define cv (make-condition-variable))
(define m (make-mutex))
;; Thread - Do something, then let main thread know when we are done
(thread-start!
(make-thread
(lambda ()
(write "started thread")
(thread-sleep! 3000)
(write "thread done")
(condition-variable-broadcast! cv))))
;; Main thread - wait for thread to broadcast it is done
(mutex-lock! m)
(mutex-unlock! m cv) ;; Wait on cv
(write "main thread done")
(thread-sleep! 500)