Casts and some suggestions to avoid them

Marco Leise Marco.Leise at gmx.de
Wed Apr 9 04:30:39 PDT 2014


Am Tue, 08 Apr 2014 21:30:08 +0000
schrieb "Colden Cullen" <ColdenCullen at gmail.com>:

> One issue I've had huge amounts of trouble with is casting to and 
> from shared. The primary problem is that most of phobos doesn't 
> handle shared values at all.
> 
> If there was some inout style thing but for shared/unshared 
> instead of mutable/immutable/const that would be super helpful.

Can you explain what level of atomicity you expect?

1) what atomicity?
2) atomic operations on single instructions
3) the whole Phobos function should be atomic with respect to
   the shared values passed to it
4) some mutex in your "business logic" will make sure there
   are no race conditions

Shared currently does two things I know of (besides
circumventing TLS):
- simply tag a variable as "multi-threaded" so you don't
  forget that fact
- the compiler will not reorder or cache access to it

So what would it add to Phobos if everything accepted shared?
In particular how would that improve thread-safety, which is
the aim of marking things shared?
It doesn't, because only the functions in core.atomic make
sense to accept shared. The reason is simply that they are
running a single instruction on a single shared operand and not
a complete algorithm. Anything longer needs to be implemented
with thought put into race conditions.

Example:

x = min(a, b);

Say a == 1 and b == 2. The  function would load a from memory
into a CPU register, then some other thread changes a to 3,
then the function compares the register content with b and
returns 1, which is no longer correct at this point in time. 

It is not that it can never be what you want, but that min()
alone cannot decide what is right for YOUR code.

So instead of passing shared values to generic algorithms, we
only really need UNSHARED!

-- 
Marco



More information about the Digitalmars-d mailing list