Fully transitive const is not necessary
Sean Reque
seanthenewt at yahoo.com
Thu Apr 3 16:38:29 PDT 2008
Steven Schveighoffer Wrote:
> "Sean Kelly" wrote
> > == Quote from Janice Caron article
> >> ...which raises an interesting point. Can "synchronized" be used on a
> >> const object? What about an invariant object?
> >
> > They'll work just fine with const objects in D. Object monitors in D
> > currently
> > live outside the const checking scheme.
>
> Oh so you mean Walter couldn't implement mutexes without logical const huh?
> I think this part of the system should be ripped out and you should have to
> pass mutexes along with objects everywhere you want to ensure thread safety
> and const is transitive. That's easier and less obfuscated, right?
>
> -Steve
>
>
The whole point of invariant objects and pure functions in terms of thread safety is that you don't need any form of synchronized data access. If, for instance a piece of data is guaranteed not to change, then two cores can hold two separate copies of the same data in each of their local caches instead of having to fetch the same data from an external source. Requiring synchronization on all const objects would entirely defeat optimizations like these.
The end result is, don't use const, invariant, or pure if you plan on modifying internal data on an object. A caching calculator, for instance, is inherently not thread safe, because one thread might cause the calculator to write to the cache at the same time another thread reads from it, so the calculator should never be allowed to be const or invariant. If I understand correctly, Walter wants the compiler to be able to make assumptions on an invariant object that would not be possible if it had mutable members.
I think that the ideas of pure and invariant will be very valuable in the end and one of D's strong selling points. It will require more careful library design though, and some designs and features, such as caching calculations or synchronizing memory access, will simply not be usable with it.
More information about the Digitalmars-d
mailing list