mirror of
https://github.com/justinethier/cyclone.git
synced 2025-07-04 03:36:34 +02:00
Proper use of condition variable
This commit is contained in:
parent
f432900cb7
commit
af40c7cd8d
1 changed files with 28 additions and 12 deletions
|
@ -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")
|
||||
(let loop ()
|
||||
(mutex-lock! m)
|
||||
(write "register waiting thread cv")
|
||||
(cond
|
||||
(*done*
|
||||
(trace "waiting thread done")
|
||||
(mutex-unlock! m))
|
||||
(else
|
||||
(trace "waiting thread - waiting for cv")
|
||||
(mutex-unlock! m cv)
|
||||
(write "waiting thread done"))))
|
||||
(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))))
|
||||
|
|
Loading…
Add table
Reference in a new issue