compilation error with shared ReadWriteMutex

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 30 05:25:54 PDT 2016


On 6/30/16 8:18 AM, jj75607 wrote:
> I wrote shared class with rwmutex
>
>   import core.sync.rwmutex;
>   shared class Shared
>   {
>       ReadWriteMutex rwmutex;
>       int[] items;
>
>       this()
>       {
>           rwmutex = new ReadWriteMutex();
>       }
>   }
>
> But it fails with:
>
>   Error: cannot implicitly convert expression (new
> ReadWriteMutex(cast(Policy)1)) of type core.sync.rwmutex.ReadWriteMutex
> to shared(ReadWriteMutex)
>
> I add `shared' keyword to the `rwmutex' variable
>
>   shared class Shared
>   {
>       shared(ReadWriteMutex) rwmutex;

You don't need to mark this shared, because the entire class is shared, 
all members are implicitly marked shared.

>       int[] items;
>
>       this()
>       {
>           rwmutex = new shared(ReadWriteMutex)();

This is what fixes the original compilation error. You are constructing 
a shared object, so it can be correctly assigned to the shared member.

>       }
>   }
>
> And got another compilation error:
>
>   Error: non-shared method core.sync.rwmutex.ReadWriteMutex.this is not
> callable using a shared object

Yep. Nothing in core.sync can be marked shared. Ironic, isn't it?

In seriousness, someone need to work on getting core.sync shareable. The 
library was written way before shared was a thing (it's actually from D1 
days). It makes no sense that Mutexes and the like cannot be shared. 
That is their core purpose.

> How can I use shared class with mutex correctly?

casting:

rwmutex = cast(shared) new ReadWriteMutex();

...

(cast()rwmutex).lock(); // casts away all attributes.

Note, beware of removing const/immutable attributes (i.e. don't do this 
in functions marked const or immutable).

-Steve


More information about the Digitalmars-d-learn mailing list