Threading with fork/semaphore/share

Q&A's, tips, howto's
Locked
Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Threading with fork/semaphore/share

Post by Jeff »

I wrote a couple of functions to automate assigning a (share) and a (semaphore) and blocking when ready to get the data from the child process. It only works on unix/osx, though, since it uses fork and releases the share.

Code: Select all

(define-macro (spawn)
  (letn ((expr (args 0))
         (sem (semaphore))
         (res (share))
         (pid (fork (begin
                      (let ((res-val (eval expr)))
                        (semaphore sem -1)
                        (share res (source 'res-val))
                        (exit))))))
    (list pid sem res)))

(define (receive proc sym-result , res-val serialized-result)
  (let ((pid (proc 0)) (sem (proc 1)) (res (proc 2)))
       (semaphore sem 1)
       (wait-pid pid)
       (setq serialized-result (share res))
       (share nil res)
       (semaphore sem 0)
       (if (catch (eval-string serialized-result) 'res-val)
           res-val 'invalid-result)))
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

jrh
Posts: 36
Joined: Mon Nov 14, 2005 9:54 pm
Location: Portland, Oregon

Post by jrh »

Why do you find it necessary to use a macro for this?

Jeff
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Post by Jeff »

To avoid having to quote arguments to the expression passed, since it is getting wrapped in other commands. Also, in the version that I use, I have some extra stuff in there that uses unify to match against what is returned and eval other params based on which phrase matches (like ML).
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Locked