www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - shared members and castings

reply nrgyzer <nrgyzer gmail.com> writes:
Hi guys,

is there any way to use shared members without casting them? Fox example:

class Example {

    private shared HashSet!(string) ex;

    ...

    this() {
        ex = cast(shared) new HashSet!(string)();
    }

    void write() {
        foreach (ref c; cast(HashSet!(string)) ex) {
            std.stdio.writeln(c);
        }
    }
}

Without casting, I always get some errors. My classes contains many different
collections and values, so I've many casts which makes the code at some points
a bit unclear. Is there any way to prevent the casting from/to shared objects?
Nov 12 2011
next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
First one can be:
ex = new shared(HashSet!(string));

I don't know about foreach/opApply, I guess each library has to
implemented shared support manually?
Nov 12 2011
prev sibling next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
Btw a quicker way to cast away shared is to use:

foreach (ref c; cast()ex)
Nov 12 2011
prev sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Sat, 12 Nov 2011 15:20:54 -0500, nrgyzer <nrgyzer gmail.com> wrote:

 Hi guys,

 is there any way to use shared members without casting them? Fox example:

 class Example {

     private shared HashSet!(string) ex;

     ...

     this() {
         ex = cast(shared) new HashSet!(string)();
     }

     void write() {
         foreach (ref c; cast(HashSet!(string)) ex) {
             std.stdio.writeln(c);
         }
     }
 }

 Without casting, I always get some errors. My classes contains many  
 different
 collections and values, so I've many casts which makes the code at some  
 points
 a bit unclear. Is there any way to prevent the casting from/to shared  
 objects?
The objects have to implement shared methods directly. From your sample code, I assume you are using dcollections. I have not yet thought about how to tackle shared versions of containers. Certainly, your code is not a good way to do it, since you are not doing any synchronization. The issue is, if a container is shared, you may only call shared methods on it. I have no shared methods in dcollections, because they would be simple wrappers for synchronizing the methods on the container. I would like to find an automatic way to do this rather than use boilerplate everywhere. I also would like to investigate shared-aware containers that are safer to use (possibly lock-free) than simply synchronizing all methods. -Steve
Nov 14 2011