Shared

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon May 13 16:20:30 UTC 2019


On Monday, May 13, 2019 9:52:02 AM MDT Dominikus Dittes Scherkl via 
Digitalmars-d wrote:
> On Saturday, 11 May 2019 at 15:24:19 UTC, Jonathan M Davis wrote:
> > All that really would do is add a bit of extra syntax around
> > locking a mutex and casting away shared.
>
> No, it makes it possible to use mutex in safe functions without
> needing to cast and which the compiler CAN guarantee to really be
> safe.

Actually, it doesn't. All you've done is lock a mutex and cast away shared.
There is no guarantee that that mutex is always used when that object is
accessed. There could easily be another piece of code somewhere that casts
away shared without locking anything at the same time. And even if this were
the only mechanism for removing shared, you could easily use it with the
same object and a completely different mutex in another piece of code,
thereby making the mutex useless. The type system has no concept of
ownership and no concept of a mutex being associated with any particular
object aside from synchronized classes (and those don't even currently
require that the mutex always be used). And even if the compiler could check
that all uses of a particular variable were locked with a mutex, that still
wouldn't be enough, because other references to the same data could exist.
So, with the construct you've proposed, there's no way for the compiler to
guarantee that no other thread is accessing the data at the same time. All
it guarantees is that a mutex has been locked, not that it's actually
protecting the data.

The only proposal that we've had thus far that is actually able to make
enough guarantees to safely remove shared is the synchronized classes
proposal in TDPL (which has never been implemented). The compiler would only
be able to remove shared at all with TDPL synchronized classes, because it
would guarantee that no references to the data directly in the class escaped
the class, and even then, it could only safely remove the outer layer of
shared, because anything that isn't directly in the class could still have
references to it elsewhere. So, TDPL synchronized classes would actually be
very limited in usefulness, because they simply can't guarantee enough to
strip much of shared away, and they're only able to do that much because of
how restrictive they are. Something as free-form as simply indicating that a
mutex is locked in a block of code is nowhere near enough to guarantee that
accessing any variables in that code is thread-safe.

- Jonathan M Davis





More information about the Digitalmars-d mailing list