A few questions about safe concurrent programming assumptions

Jonathan M Davis jmdavisProg at gmx.com
Sun Oct 6 18:43:30 PDT 2013


On Thursday, October 03, 2013 08:34:00 Nicholas Smith wrote:
> * Reads and writes to shared variables with a size equal to or
> less than the word size of the machine are atomic and are visible
> to all other threads immediately.

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. If you use shared, then you _must_ use mutexes or 
synchronized blocks to protect access to any shared variables - 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.

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.

TDPL does say some stuff about shared and memory barriers, but that has never 
been implemented, and given the performance costs that it would incur, it's 
highly likely that it will never be implemented.

You pretty much have to treat shared like you'd treat any variable in 
C/C++/Java/C#/etc. which was being accessed from multiple threads.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list