A few questions about safe concurrent programming assumptions
Jonathan M Davis
jmdavisProg at gmx.com
Sun Oct 6 23:30:51 PDT 2013
On Monday, October 07, 2013 07:26:02 Nicholas Smith wrote:
> Thanks Jonathon, these are the kinds of warnings I was looking
> for.
>
> > There are _no_ guarantees of atomicity with shared. Yes, on some
> > architectures, writing a word size might be atomic, but the
> > language
> > guarantees no such thing.
>
> I was looking narrowly at x86, which I *think* such a statement
> is safe to say for. But you're absolutely right that I should
> probably safeguard against the possibility that something could
> go wrong there.
>
> > either that or
> > you have to mess around with core.atomic, which is the kind of
> > code that is
> > _very_ easy to screw up, so it's generally advised not to
> > bother with
> > core.atomic unless you actually _need_ to.
>
> It will at least ensure sequential consistency, atomic
> load/store, and atomic operations (via atomicOp), will it not?
You can do atomic operatios via core.atomic, but they're easy to use
incorrectly, and I'm not very familiar with them, so I couldn't tell you much
more than whatever the docs say.
> > shared really doesn't guarantee anything. It just means that
> > you can access
> > that object across threads, which means that you must do all
> > the work to make
> > sure that it's protected from being accessed by multiple
> > threads at the same
> > time.
>
> Fair enough. It will force the compiler to write to memory
> immediately though, rather than keep shared values sitting in
> registers, correct?
I don't believe that shared makes any more guarantees in that regard than
happens with thread-local variables. All shared really does is make it so that
you can access the variable from multiple threads instead of it being thread-
local and make it so that the compiler won't make optimizations based on the
assumption that only one thread can access the variable.
If you use mutexes or sychronized blocks to protect all access of shared
variables, you shouldn't have to worry about any threading issues. If you
don't, then you're almost certainly going to run into trouble. core.atomic is
an alternative, but again, you have to use it correctly, and it's easy to
screw up.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list