[plt-scheme] fluid-let and threads

From: Ryan Culpepper (ryanc at ccs.neu.edu)
Date: Thu Apr 17 17:47:41 EDT 2008

'fluid-let' is essentially 'set!'.

Would the behavior of your program (and its variants) make more sense 
if you had written it as the following way to start with?

   (define x 1)
   (set! x 2)
   (thread (lambda () (printf "~a~n" x)))
   (set! x 1)

They're essentially the same. Will the old thread mutate 'x' back 
before the new thread reads it? Who knows? In the original program, 
either outcome is possible. If you add in delays (sleep) you can 
influence the probabilities of the different choices. If you add in 
synchronization you can force one outcome or the other.

But it's just the standard story of multiple threads with shared 
mutable state.

('fluid-let' does a little more work to handle exceptions and 
continuation jumps, but those don't come into play in your example.)

If you want a kind of dynamic binding that works well across threads, 
you should look at PLT Scheme's parameters (search Help Desk for 
'make-parameter' and 'parameterize'), as in:

   (define x (make-parameter 1))
   (parameterize ((x 2))
     (thread (lambda () (printf "~a~n" (x)))))

Ryan


On Apr 17, 2008, at 4:57 PM, Eric Tanter wrote:

> Hi,
>
> I am trying to understand the semantics of fluid-let in the presence 
> of threads.
>
> First, consider this program:
>
> (define x 1)
> (fluid-let ((x 2))
>   (thread (lambda()
>             (printf "~a~n" x)
>             )))
>
> prints a 1, which suggests that a thread created within a fluid-let 
> does not see the fluid binding. Ok, that's a possibility.
>
> But, it turns to be different if I add a bit of synchronization 
> between the two threads. First, a variant that gives the same result 
> (1):
>
> (define x 1)
> (define ch (make-channel))
> (fluid-let ((x 2))
>   (thread (lambda()
>             (printf "~a~n" x)
>             (channel-put ch 'ok))))
> (channel-get ch)
>
> Now, consider I move the channel-get within the fluid-let:
>
> (define x 1)
> (define ch (make-channel))
> (fluid-let ((x 2))
>   (thread (lambda()
>             (printf "~a~n" x)
>             (channel-put ch 'ok)))
>   (channel-get ch)
> )
>
> I get 2!! meaning the value bound to x in the printf of the created 
> thread is now 2. Just commenting out the "(channel-get ch)" 
> expression, and I am back to getting a 1.
>
> Any clarification is more than welcome!
>
> Thank you,
>
> -- Éric, completely puzzled
>
> PS: using DrScheme 372 language 
> MzScheme_________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme



Posted on the users mailing list.