Semaphores and shared memory.

Started by statik, August 12, 2005, 07:30:39 PM

Previous topic - Next topic

statik

Here's the code:



#!/usr/bin/newlisp

(context 'MAIN)

;; Check for a win32 platform

(if (> (& (last (sys-info)) 0xF) 4)
   (begin
      (println "Please run this application under unix.")
      (exit)
   )
)

;; Set constants

(constant   'signal 1
            'release 0
            'wait -1
)

(define (left-hand x)
   (println "left-hand")
   (set 'val 0)
   (while (< val x)
      (semaphore left-semaphore wait)
      (println (set 'val (share data)) "<--")
      (semaphore right-semaphore signal)
   )
   (exit)
)

(define (right-hand x)
   (println "right-hand")
   (for (val 1 x)
      (semaphore right-semaphore wait)
      (println "-->" (share data x))
      (semaphore left-semaphore signal)
   )
   (exit)
)

(define (start x)
   (println "Application Running...")

   ;; Allocate and fill shared memory
   (set 'data (share))
   (share data 0)

   ;; Create Semaphores for both right/left hands
   (set 'left-semaphore (semaphore))
   (set 'right-semaphore (semaphore))

   ;; Start threads
   (set 'left-process-id (fork (left-hand x)))
   (set 'right-process-id (fork (right-hand x)))

   ;; Move left hand
   (semaphore left-semaphore signal)

   ;; Wait for threads to finish
   (wait-pid left-process-id)
   (wait-pid right-process-id)

   ;; And finally, we release the semaphores
   (semaphore left-semaphore release)
   (semaphore right-semaphore release)
)

(start 1000)

(exit)


Now, I've tried to follow the manual yet, the out put of the program doesnt look right:



tmace:/src tmace$ ./semaphore.lsp
Application Running...
left-hand
0<--
right-hand
-->1000
1000<--
-->1000
^C
user reset - in function wait-pid
called from user defined function start
(c)ontinue, (d)ebug, e(x)it, (r)eset:
user reset - in function semaphore
called from user defined function right-hand
called from user defined function start
(c)ontinue, (d)ebug, e(x)it, (r)eset:x
tmace:/src tmace$ -->1000

tmace:/src tmace$


If anyone here could explain what is actually going on, i'd appreciate it.
-statik

Lutz

#1
In the definition of 'right-hand' change to:



(println "-->" (share data val)) ; val instead of x


then it runs fine



Lutz

statik

#2
Hahaha, yeah, someone pointed that out just a moment ago! I spent a long time trying to find that... :)
-statik