Proper use of condition variable

This commit is contained in:
Justin Ethier 2016-02-19 23:24:40 -05:00
parent f432900cb7
commit af40c7cd8d

View file

@ -1,33 +1,49 @@
;;;; An example of using condition variable broadcast to wake other threads.
;;;; An example of using a condition variable to wake other threads.
(import (scheme base)
(scheme read)
(scheme write)
(srfi 18))
(define *done* #f)
(define cv (make-condition-variable))
(define m (make-mutex))
(define (trace msg)
(display msg)
(newline))
;; Thread - Sleep, then wake other threads up via broadcast
(thread-start!
(make-thread
(lambda ()
(write "started thread")
(thread-sleep! 3000)
(set! *done* #t)
(condition-variable-broadcast! cv)
(write "thread done"))))
(trace "broadcast thread done"))))
;; Thread - wait for broadcast
(thread-start!
(make-thread
(lambda ()
(write "started waiting thread")
(mutex-lock! m)
(write "register waiting thread cv")
(mutex-unlock! m cv)
(write "waiting thread done"))))
(let loop ()
(mutex-lock! m)
(cond
(*done*
(trace "waiting thread done")
(mutex-unlock! m))
(else
(trace "waiting thread - waiting for cv")
(mutex-unlock! m cv)
(loop)))))))
;; Main thread - wait for broadcast
(mutex-lock! m)
(mutex-unlock! m cv) ;; Wait on cv
(write "main thread done")
(thread-sleep! 500)
(let loop ()
(mutex-lock! m)
(cond
(*done*
(mutex-unlock! m)
(thread-sleep! 500)
(trace "main thread done"))
(else
(mutex-unlock! m cv) ;; Wait on cv
(loop))))