Initial commit of newLISP.
[newlisp.git] / examples / prodcons.lsp
blob73d0c62c0cf19c3927918f12d2a808ed2cb93357
1 #!/usr/bin/newlisp
3 # prodcons.lsp - Producer/consumer
5 # this program only runs on Linux/UNIX
7 # usage of 'fork', 'wait-pid', 'semaphore' and 'share'
9 (if (> (& (last (sys-info)) 0xF) 4)
10 (begin
11 (println "this will not run on Win32")
12 (exit)))
15 (constant 'wait -1 'signal 1 'release 0)
17 (define (consumer n)
18 (set 'i 0)
19 (while (< i n)
20 (semaphore cons-sem wait)
21 (println (set 'i (share data)) " <-")
22 (semaphore prod-sem signal))
23 (exit))
25 (define (producer n)
26 (for (i 1 n)
27 (semaphore prod-sem wait)
28 (println "-> " (share data i))
29 (semaphore cons-sem signal))
30 (exit))
33 (define (run n)
34 (set 'data (share))
35 (share data 0)
37 (set 'prod-sem (semaphore)) ; get semaphores
38 (set 'cons-sem (semaphore))
40 (set 'prod-pid (fork (producer n))) ; start threads
41 (set 'cons-pid (fork (consumer n)))
42 (semaphore prod-sem signal) ; get producer started
44 (wait-pid prod-pid) ; wait for threads to finish
45 (wait-pid cons-pid) ;
46 (semaphore cons-sem release) ; release semaphores
47 (semaphore prod-sem release))
50 (run 10)
52 (exit)