From af40c7cd8d014b7539027f484b03f25af0f99d6c Mon Sep 17 00:00:00 2001 From: Justin Ethier Date: Fri, 19 Feb 2016 23:24:40 -0500 Subject: [PATCH] Proper use of condition variable --- examples/threading/cv-broadcast.scm | 40 ++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/examples/threading/cv-broadcast.scm b/examples/threading/cv-broadcast.scm index 924d6c15..05db2114 100644 --- a/examples/threading/cv-broadcast.scm +++ b/examples/threading/cv-broadcast.scm @@ -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))))