[plt-scheme] Re: Using LibFFI along with threads

From: Eli Barzilay (eli at barzilay.org)
Date: Tue Jul 17 09:22:57 EDT 2007

On Jul 17, Hans Oesterholt-Dijkema wrote:
> The problem with C libraries is that they do not always provide
> callback scenarios, nor other ways to divide up functions in smaller
> parts to get some 'time slicing'.

You should have *some* way to synchronize threads in C -- my point was
that the one that is easiest to implement in C is the right solution.

BTW -- here's an alternative:

Creating a subprocess is easy, and probably not much more expensive
than a thread.  Specifically, it sounds like you're paying enough
price for DB operations that the difference between a system thread
and a system process would be insignificant.  So it should be quite
easy to do what you want to do by running a mzscheme subprocess, and
communicate with it using stdin/stdout.  This way you don't need to
deal with ports, tcp, or sockets.  The subprocess doesn't even need to
load any special files -- you can feed it the code you want.  Here's a
simple sketch:

  (define (async/channel form)
    (let-values ([(p pout pin perr)
                  (subprocess #f #f (current-error-port)
                              (find-system-path 'run-file)
                              "-mve" (format "(write (let () ~s))" form))]
                 [(c) (make-channel)])
      (close-output-port pin)
      (thread (lambda ()
                (channel-put c (read pout))
                (unless (sync/timeout 10 p)
                  (subprocess-kill p #f)
                  (unless (sync/timeout 10 p)
                    (subprocess-kill p #t)))))

and an example:

  (define (run-fib n)
    (async/channel `(begin (define (fib n)
                             (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
                           (fib ,n))))
  (map channel-get (map run-fib '(30 31 32 33)))

This can be made much better.  (For example, you can send compiled
code over to the subprocess, you can add a mechanism that keeps
running processes around to avoid process creation overhead, you can
have state in threads, etc.)

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!

Posted on the users mailing list.