Fully transitive const is not necessary

Bill Baxter dnewsgroup at billbaxter.com
Wed Apr 2 01:11:09 PDT 2008


Janice Caron wrote:
> On 01/04/2008, Craig Black <craigblack2 at cox.net> wrote:
>> Walter/Andrei are under the impression that transitive const is necessary
>>  for multiprogramming, but they have not presented a detailed explanation
>>  about why it is necessary.
> 
> It hardly needs a detailed explanation. In fact it's trivial to
> understand. Watch:
> 
>     // in C++
>     void f(const C &c)
>     {
>         c.some.deeply.nested.but.reachable.var++;
>     }
> 
> In a multithreaded program, a thread switch may occur between the read
> and the write of the read/write cycle that is ++. If that happens,
> you're screwed.
> 
>     // in D
>     void f(const C c)
>     {
>         c.some.deeply.nested.but.reachable.var++; /*ERROR*/
>     }
> 
> In D, such dodgy code just won't compile.

But this dodgy code will

void f(const C c) {
     some_global++;
}

So const isn't a guarantee of thread safety.

And watch this:

void f(const C c) {
     assert(
	c.we_like_const == c.we_like_const,
         "Oops!  "
	"Some other thread must have changed c "
	"while we weren't looking!");
}

Might just assert. Const gives no guarantee that values won't change out 
from under you when used in a multithreaded environment.

And watch this:
void f(C c) {
     int x = c.get_some_value();
}

Hey! That probably *is* thread safe, and it didn't even use const at all.

So it seems "const is necessary for multiprogramming" is not quite the 
whole truth, which was all the original poster was talking about. 
'Course that may be a strawman.  I don't know that Walter has ever said 
precisely that.  He's usually phrases it more like "it will be important 
for what's coming".

I can see invariant having some value in conjunction with pure, but I 
also suspect that invariant, being so strict, is also something that 
will not get used a lot outside of simple constants and code carefully 
designed for running in parallel.  Like what Don's said.

--bb



More information about the Digitalmars-d mailing list