Shared

Graham St Jack Graham.StJack at internode.on.net
Mon Aug 2 00:14:42 PDT 2010


On 02/08/10 02:16, dsimcha wrote:
> == Quote from dsimcha (dsimcha at yahoo.com)'s article
>    
>> I've reread the relevant TDPL chapter and I still don't quite understand the
>> following:
>> 1.  What is shared?  Is it simply a piece of syntactic salt to make it hard to
>> share data across threads by accident, or is there more to it?
>> 2.  Is it fully or mostly implemented?
>>      
> Sorry, accidentally submitted the post before I was done.
>
> 3.  How does casting to and from shared work?  Under what circumstances can
> unshared data be cast to shared?  Under what circumstances can shared data
> implicitly be cast to unshared?
>    

I too have had a lot of trouble using shared, but I am currently giving 
it another serious try.

My observations so far are that the compiler's handling of it is a bit 
buggy, but that it seems to more-or-less work, and will be usable when 
the necessary library code is updated to use it - specifically Mutex, 
Condition and concurrency's Mailbox.

You are not supposed to need to routinely cast to-and-from shared. Value 
and immutable types should implicitly convert to/from shared, and 
synchronized types should implicitly convert to shared. So for example, 
a string is ok because it is a value and a pointer to immutable data.

I have found the following approach to work ok:

import std.stdio;
import std.traits;
import std.conv;


synchronized class Channel(T) if (!hasAliasing!T)
{
     void add(T t) { }
}

alias Channel!string MyChannel1;
alias shared MyChannel1 MyChannel;

void main() {
     auto channel = new MyChannel();

     channel.add("hello");
}


The key trick for me was to use an alias to wrap the shared up with the 
data type. For some reason the compiler didn't like it when I used a 
templated type, but the second layer of aliases placated it - hopefully 
that is a bug that will be fixed soon.

I hope that helps.

-- 
Graham St Jack



More information about the Digitalmars-d mailing list