On 10/04/2016 09:22 PM, Begah wrote:
I seem to be missing something.
It seems that if you want to create a shared object of a structure ( or
class ), then I have to copy every functions and add "shared" to it.
This seems way more work than it should.
For example why can't this simply work :

  class Image {
    string name;
    int contents;

    this(string name, int contents) {
        this.name = name;
        this.contents = contents;
    }

    void printContents() {
        writeln(name, " : ", contents);
    }

    void changeContents(int newContents) {
        this.contents = newContents;
    }
  }

  void main()
  {
    Image im = new Image("Test", 15);
    im.printContents();
    im.changeContents(45);
    im.printContents();

    shared Image imShared = new shared Image("Test2", 80);
    imShared.printContents();
    imShared.changeContents(6);
    imShared.printContents();
  }

Non-`shared` methods are not required to be somehow thread-safe at all. So they can't be allowed to be called on `shared` objects.

The compiler can't automatically ensure thread-safety, because it can't know what can run in parallel and what can't.

How can I make a method that accepts being called by both a shared and
non-shared object, to prevent having to copy methods and adding a "shared"?

I would have thought that you can call a shared method on an unshared object. Apparently not. There's probably a reason for that, but I don't see it at the moment.

I am not looking for an explanation for how to handle multi-threading (
synchronization and so on ). I am looking to use pre-coded classes and
structures ( without using __gshared ) with non-shared and shared objects.

Ensure thread-safety and cast `shared` away.

Reply via email to