forked from justinethier/cyclone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcv-broadcast.scm
49 lines (44 loc) · 1.09 KB
/
cv-broadcast.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
;;;; 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 ()
(thread-sleep! 3)
(set! *done* #t)
(condition-variable-broadcast! cv)
(trace "broadcast thread done"))))
;; Thread - wait for broadcast
(thread-start!
(make-thread
(lambda ()
(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
(let loop ()
(mutex-lock! m)
(cond
(*done*
(mutex-unlock! m)
(thread-sleep! 0.5)
(trace "main thread done"))
(else
(mutex-unlock! m cv) ;; Wait on cv
(loop))))