Subject: Re: bug#21887: 'monitor' form broken

From: Andy Wingo <[email-masked]>
Date: Fri, 24 Jun 2016 18:04:06 +0200

Hi Taylan,

On Thu 12 Nov 2015 16:29, [email-masked] (Taylan Ulrich "Bayırlı/Kammer") writes:

> It seems that the 'monitor' form is currently a no-op.  The form
>
>     (par-for-each (lambda (x)
>                     (monitor
>                       (foo)))
>                   xs)
>
> should be functionally equivalent to
>
>     (let ((mutex (make-mutex)))
>       (par-for-each (lambda (x)
>                       (with-mutex mutex
>                         (foo)))
>                     xs))
>
> but currently becomes
>
>     (par-for-each (lambda (x)
>                     (let ((mutex (make-mutex)))
>                       (with-mutex mutex
>                         (foo))))
>                   xs)
>
> which is ineffective.
>
> I don't know what's the best way to fix this.  The simplest thing that
> comes to my mind is something along the lines of:
>
>     (define-syntax monitor
>       (lambda (stx)
>         (syntax-case stx ()
>           ((_ body body* ...)
>            (let ((uuid (generate-uuid)))
>              #`(with-mutex (mutex-with-uuid #,uuid)
>                  body body* ...))))))
>
> where mutex-with-uuid looks it up from a hash table at run-time and
> instantiates it when it doesn't exist, this operation also being
> synchronized across threads, like:
>
>     (define mutex-table (make-hash-table))
>
>     (define mutex-table-mutex (make-mutex))
>
>     (define (mutex-with-uuid uuid)
>       (with-mutex mutex-table-mutex
>         (or (hash-ref mutex-table uuid)
>             (let ((mutex (make-mutex)))
>               (hash-set! mutex-table uuid mutex)
>               mutex))))
>
> If that looks OK, I can try to make a proper patch from it.  I'm not
> sure what I'd use in place of `generate-uuid' though.  Would `gensym' be
> good enough?

You're totally right on all points.  Please do prepare a patch :)  I
wish we could do something faster for the "embedded" mutex but
correctness should come first.

Cheers,

Andy