[plt-scheme] Thread synchronization for dummies

From: Anthony Cowley (acowley at seas.upenn.edu)
Date: Thu May 28 15:35:20 EDT 2009

Eastlund<carl.eastlund at gmail.com> wrote:
> It has been pointed out to me privately that my response isn't really
> answering your question, which is not simply "can threads, channels,
> and other synchronization primitives be strung together to make a
> synchronized function", but rather "is there an automatic way to
> declare a function as synchronous".  I don't believe there is (and
> sorry for my misreading).  However, there is probably a simple (for
> someone familiar with these primitives) way to write a
> define/synchronized macro.  If I can come up with one that you can
> simply copy/paste into your code (and that can later be added to a
> reusable library) I'll let you know.

I misread it, too! I thought Erich had a mutual synchronization
question. Here is a macro solution.

Anthony

#lang scheme

(define-syntax define-synchronized
  (syntax-rules ()
    [(_ (name args ...) body ...)
     (define name
       (let ((m (make-semaphore 1)))
         (λ(args ...)
           (semaphore-wait m)
           body ...
           (semaphore-post m))))]))

(define-synchronized (foo x)
  (printf "foo ~a starting..." x)
  (flush-output)
  (sleep 1)
  (printf "done~n"))

(define t1 (thread (λ() (foo 1)(foo 1)(foo 1))))
(define t2 (thread (λ() (foo 2)(foo 2)(foo 2))))

(thread-wait t1)
(thread-wait t2)


Posted on the users mailing list.