-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
producer-consumer.scm
54 lines (50 loc) · 1.39 KB
/
producer-consumer.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
50
51
52
53
54
;; An example program having multiple producers concurrently writing to a queue
;; and a single consumer reading from the queue.
(import
(scheme base)
(scheme read)
(scheme write)
(srfi 18))
;; Global queue and a lock to coordinate access to it.
;; Note ->heap is used to ensure any objects accessed by multiple threads are
;; not on a thread's local stack, since those objects can be moved at any time
;; by the thread's minor GC.
(define *queue* (->heap (list)))
(define *lock* (make-mutex))
(define (producer)
(let loop ((n 100))
(cond
((> n 0)
(mutex-lock! *lock*)
(display (cons 'a *queue*))
(newline)
(set! *queue* (->heap (cons (->heap n) *queue*)))
(mutex-unlock! *lock*)
(loop (- n 1)))
(else
(display "producer thread done")
(newline)))))
(define (consumer)
(let loop ()
;(display (list (null? *queue*) *queue*))
;(newline)
(define sleep? #f)
(mutex-lock! *lock*)
(cond
((not (null? *queue*))
(display (car *queue*))
(newline)
(set! *queue* (cdr *queue*)))
(else
(display "consumer sleeping")
(newline)
(set! sleep? #t)))
(mutex-unlock! *lock*)
(if sleep? (thread-sleep! 1))
(loop)))
(thread-start! (make-thread producer))
(thread-start! (make-thread producer))
(thread-start! (make-thread producer))
;(producer)
(consumer)
;(read)