chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Some questions about concurrency (mostly)


From: Jörg F. Wittenberger
Subject: Re: Some questions about concurrency (mostly)
Date: Fri, 6 Nov 2020 17:20:04 +0100

Am Thu, 05 Nov 2020 23:22:09 +0100
schrieb Fredrik Appelberg <fredrik@appelberg.me>:

> 3. I'm new to dynamic-wind. If I wanted to create a general form for
>    executing a thunk protected by a mutex, would this be a good idea?
> 
>      (define (with-lock mutex thunk)
>        (dynamic-wind
>            (lambda () (mutex-lock! mutex))
>                thunk
>                (lambda () (mutex-unlock! mutex)))))
> 
>    I read somewhere that the before- and after-guards might execute
>    multiple times, but then again I'm not really sure under what
>    circumstances so I might be way off.

This approach is bound to fail badly.

It works just as long as there are a) no exceptions raised in `thunk`
b) no code, not even in a library does any `call/cc`.  Including
`call/cc` hidden in exception handlers (srfi-12, srfi-34 etc.)

NEVER DO THIS!

You need this:

   (define with-lock mutex thunk
      (handle-exceptions
        exn
        (begin
          find out whether you can safely unlock the mutex or
          clean up the damage done by partially updating the resource
          (mutex-unlock! mutex) ;; if appropriate
          either `(raise exn)` or return some value)
        (mutex-lock! mutex)
        modify resource
        (mutex-unlock! mutex)))




reply via email to

[Prev in Thread] Current Thread [Next in Thread]