[plt-dev] thread-specifics [PATCH]

From: Matthew Flatt (mflatt at cs.utah.edu)
Date: Tue Mar 3 15:52:08 EST 2009

At Tue, 3 Mar 2009 15:29:44 -0500 (EST), Dimitris Vyzovitis wrote:
> On Tue, 3 Mar 2009, Matthew Flatt wrote:
> >> Well, I take it you mean having a global weak-hash table here?
> >
> > Yes.
> >
> >> That is
> >> rendezvous in itself, because it has to be accessed and implement a
> >> synchronization protocol to it.
> >
> > I concede that when you share anything, whether a hash table or a
> > thread references, that there is some sort of rendezvous. But I don't
> > see why it's more of a problem with a hash table.
> I can see a few problems here:
> 1) The key in the value problem - the threads may well refer to themselves
>     this complicates the access patterns in the hashtable

Ephemerons solve this easily.

> 2) Access permissions
>     There is concurrency involved in the updates.
>     The specific access protocol provides memory consistent:
>      The owner thread can write atomically
>      Everybody can read atomically and always sees the last value placed
>       by the owner in trace causality sense.
>      The specific is asynchronous and very very cheap.

But `hash-ref' and `hash-set!' handle concurrency.

> In addition, the fact that specific is a slot that makes a lightweight 
> tool (without having to go to all this) for easily implementing common 
> synchronization patterns:  barriers, async completion tokens, thread tags, 
> etc

Here's an implementation:

 #lang scheme/base

 (provide specific-ref 

 (define specifics (make-weak-hasheq))

 (define (specific-ref th [fail (lambda () #f)])
   (let ([c (hash-ref specifics th #f)])
     (if c
         (ephemeron-value c)

 (define (specific-set! th v)
   (hash-set! specifics th (make-ephemeron th v)))

This doesn't seem complex to me.

It will be a bit slower than your patch. Still, on my machine, 1M
iterations has set and ref takes 0.33 seconds. If I replace the
implementation above with the minimal

 (define v #f)
 (define (specific-ref th [fail (lambda () #f)])
 (define (specific-set! th v2)
   (set! v2 v))

then 1M iterations takes 0.14 seconds. So the implementation seems
unlikely to be a performance bottleneck.

> Also, with regards to composition: by limiting the specific to a single 
> cell, the compositional properties can be managed at the language level 
> (scheme/base) where you are not limited by what you can reasonably do in 
> the core.

This is probably a genuine disagreement. I believe that `scheme/base'
is obliged to provide composable abstractions, and not just hooks into
the implementation.

Posted on the dev mailing list.