[plt-scheme] Thread synchronization for dummies

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

On Thu, May 28, 2009 at 3:04 PM, Erich Rast<erich at snafu.de> wrote:
>> d reference material for PLT Scheme's concurrency operations here:
>>
>> http://docs.plt-scheme.org/reference/concurrency.
>>
> Yep, I've seen this.
>
>> What I would suggest for your operation is spawning a dedicated thread
>> to handle FOO requests.  Whenever FOO gets called, it should send a
>> message to that thread, then block to wait for a response.  That
>> thread should wait for requests, and for each one should handle the
>> request and send a response before waiting for the next request.  This
>> will guarantee each request will be handled in order and will not
>> overlap.
> That sounds awfully complicated and I was hoping there was an easier
> solution. Anyway, thanks for the advice and I'll dig some more into the
> world of threads/semaphore/mutexes and whatever else there is.

Here's a traditional semaphore-based solution.

Anthony

#lang scheme

(define-values (foo bar)
  (let ((m (make-semaphore 1)))
    (values
     (λ() ; foo
       (semaphore-wait m)
       (printf "foo starting...")
       (flush-output)
       (sleep 1)
       (printf "done~n")
       (semaphore-post m))

     (λ() ; bar
       (semaphore-wait m)
       (printf "bar starting...")
       (flush-output)
       (sleep 1)
       (printf "done~n")
       (semaphore-post m)))))


;;; Tests ;;;
(define t1 (thread (λ() (foo)(foo)(foo))))
(define t2 (thread (λ() (bar)(bar)(bar))))

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


Posted on the users mailing list.