shared - no read/write access

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Mar 31 07:12:08 UTC 2019


On Monday, March 25, 2019 2:37:42 AM MDT Kagamin via Digitalmars-d wrote:
> On Thursday, 21 March 2019 at 20:50:09 UTC, Manu wrote:
> > But that's now what `shared` does... it allows (guarantees
> > even) many
> > threads mutate the same data at random with no protections.
> > By inhibiting read/write access, you force the user to obtain a
> > lock
> > (or other synchronisation method) in order to access the shared
> > data.
> > Without that, the path of least resistance is to just access
> > the data,
> > and that's a race 100% of the time, by definition (because it's
> > `shared`).
>
> Some memory accesses are thread safe, then synchronization is not
> needed.

If the compiler can guarantee thread-safety, then there shouldn't be a
problem, and nothing needs to be made illegal, but that's usually not the
case. The primary exception would be stuff like atomics, and that's typed
with shared, so you can pass shared variables to them. And it's not a
problem, because thread-safety is guaranteed.

In the cases where synchronization _is_ needed, then those operations should
be illegal, requiring the programmer to protect the object appropriately and
then cast away shared to operate on it while it's protected. That way,
nothing marked as shared is violating thread-safety, and the code where
there is a risk of violating thread-safety is @system. So, it becomes fairly
easy to grep for the portions of the code where you need to worry about
threading bugs.

And of course, because shared functions can operate on shared objects, it's
possible to do stuff like encapsulate a mutex inside an object so that it
does all of the necessary synchronization internally, and none of the code
using that object needs to do any casting or anything else that's @system to
use the shared object.

- Jonathan M Davis





More information about the Digitalmars-d mailing list