-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathsum-mutex.scm
57 lines (51 loc) · 1.31 KB
/
sum-mutex.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
55
56
57
;;;; Example of using a mutex to synchronize summing of a variable by multiple threads.
(import (scheme base)
(scheme read)
(scheme write)
(cyclone concurrent)
(srfi 18))
(define m (make-mutex))
(define *sum* 0.0)
(define (sum-loop n)
(mutex-lock! m)
(set! *sum* (+ *sum* 1))
(mutex-unlock! m)
;(swap! *sum* + 1)
(if (zero? n)
(display "thread done\n")
(sum-loop (- n 1))))
(define (sum-entry-pt)
(sum-loop (* 100 100 100)))
;; Thread - Do something, then let main thread know when we are done
(define t1 (make-thread sum-entry-pt))
(define t2 (make-thread sum-entry-pt))
(define t3 (make-thread sum-entry-pt))
(define t4 (make-thread sum-entry-pt))
(define t5 (make-thread sum-entry-pt))
(define t6 (make-thread sum-entry-pt))
(define t7 (make-thread sum-entry-pt))
(define t8 (make-thread sum-entry-pt))
(define t9 (make-thread sum-entry-pt))
(thread-start! t1)
(thread-start! t2)
(thread-start! t3)
(thread-start! t4)
(thread-start! t5)
(thread-start! t6)
(thread-start! t7)
(thread-start! t8)
(thread-start! t9)
(thread-join! t1)
(thread-join! t2)
(thread-join! t3)
(thread-join! t4)
(thread-join! t5)
(thread-join! t6)
(thread-join! t7)
(thread-join! t8)
(thread-join! t9)
(display "main thread done, sum = ")
(mutex-lock! m)
(display *sum*)
(newline)
(mutex-unlock! m)