Mallocator and 'shared'

Michael Coulombe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 10 20:32:37 PST 2017


On Friday, 10 February 2017 at 23:57:18 UTC, bitwise wrote:
> https://github.com/dlang/phobos/blob/cd7846eb96ea7d2fa65ccb04b4ca5d5b0d1d4a63/std/experimental/allocator/mallocator.d#L63-L65
>
> Looking at Mallocator, the use of 'shared' doesn't seem correct 
> to me.
>
> The logic stated in the comment above is that 'malloc' is 
> thread safe, and therefore all methods of Mallocator can be 
> qualified with 'shared'.
>
> I thought that qualifying a method as 'shared' meant that it 
> _can_ touch shared memory, and is therefore _not_ thread safe.
>
>
> The following program produces this error:
> "Error: shared method Mallocator.allocate is not callable using 
> a non-shared object"
>
> import std.experimental.allocator.mallocator;
>
> int main(string[] argv) {
>     Mallocator m;
>     m.allocate(64);
>     return 0;
> }
>
> And the above error is because it would be un(thread)safe to 
> call those methods from a non-shared context, due to the fact 
> that they may access shared memory.
>
> Am I wrong here?

A shared method means that it can only be called on a shared 
instance of the struct/class, which will have shared fields. A 
shared method should be logically thread-safe, but that cannot be 
guaranteed by the compiler. A non-shared method can touch shared 
memory, and thus should be thread-safe if it does, but can only 
be called on a non-shared instance with possibly non-shared 
fields.

shared/non-shared methods don't mix because you generally need to 
use different, less-efficient instructions and algorithms to be 
thread-safe and scalable in a shared method. In the case of 
Mallocator, there are no fields so as far as I can tell the 
attribute doesn't do much except for documentation and for 
storing references to it in other shared structs/objects.


More information about the Digitalmars-d-learn mailing list