On Wednesday, September 12, 2018 5:41:16 PM MDT James Blachly via 
Digitalmars-d-learn wrote:
> When I add the "shared" attribute to an array, I am no longer
> able to call reserve because the template won't instantiate:
>
> Error: template object.reserve cannot deduce function from
> argument types !()(shared(int[]), int), candidates are:
> /dlang/dmd/linux/bin64/../../src/druntime/import/object.d(4091):
>        object.reserve(T)(ref T[] arr, size_t newcapacity)
>
> 1. Shared modifies the type, so the template does not match. Even
> casting does not seem to work however. Is there something about
> shared that makes it unable to be taken by reference?
> 2. Is there a workaround for me to be able to preallocate the
> array?

You can't do much of anything with shared while it's shared, which is pretty
much the whole point. The way that shared needs to be used in general is
essentially

synchronized(mutexForSharedObj)
{
    auto local = cast(Type)sharedObj;
    // do stuff with local...

    // ensure that no thread-local references to local / sharedObj exist
    // before releasing the mutex
}

// shared object is now essentially unusable again

Doing pretty much _any_ operation on a shared object while it's shared
(other than atomic operations from core.atomic) is wrong, because it's not
thread-safe. The compiler prevents most operations but not as many as it
should (e.g. copying is currently legal). That will likely be fixed in the
future, but exactly what's going to happen to shared in all of the fine
details hasn't been sorted out yet. The basics work, but not all of the
details are as they should be yet.

So, if you're doing anything like calling reserve or ~= on a shared array,
then you need to protect it with the mutex that you have for it and cast
away shared first. However, if you're just dealing with constructing the
array, then what you should do is create it as thread-local and then cast it
to shared after you're done setting it up and are ready to share it across
threads (after which, all further operations on it should be protected by a
mutex or use atomics, otherwise they're not thread-safe).

- Jonathan M Davis



Reply via email to