Re: Atomicity of read/write on 64bits elements

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 03/29/04


Date: Mon, 29 Mar 2004 07:13:57 +0100

Joannes Vermorel <firstname@lastname.com> wrote:
> Thanks for the pointer to the section 5.5, that's the answer to my question:
> read/write of references are threadsafe, therefore there are no
> "inconsistent" state for references.
>
> This leads me to another question, C# and CLR aim (as far I know) to be
> "machine independent". But for 64bits architectures, assuring the atomicity
> of references read/write is at the same level than assuring the atomicity of
> read/write for double/long/ulong.
>
> I don't think being visionary if I say that 64bits architectures are going
> one day or another to replace 32bits ones. Does anyone know why read/write
> for double/long/ulong have not been defined as atomic in the C# spec ?

Because ensuring reference atomicity is likely to be easy on any
machine, whereas ensuring 64 bit atomicity on a 32 bit architecture
isn't. Double/long atomicity may well occur on 64 bit machines, but if
they'd *specified* that double/long reads were atomic, they'd be much
more complicated on 32 bit machines.

However, thread-safety is about much more than just atomicity. The
biggest problem, IMO, is data caching. Unless you have some sort of
memory barrier (eg a lock or volatile read/write) involved, there's
nothing to stop one thread from caching the value of a variable and
using that cached value, rather than going to main memory for the real
value - so long as the thread is consistent with itself, basically.

This is why you should always synchronize for shared data, or use
volatile variables. Personally I'm happier using a lock than
volatility, but that's just me.

Don't try doing clever stuff like the double-check lock algorithm
unless you're an expert (a real honest-to-goodness expert). The chances
are it won't buy you much performance, but you may well find that your
program isn't as well synchronized as you think it is.

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages

  • Re: Atomicity of read/write on 64bits elements
    ... > read/write of references are threadsafe, ... Because ensuring reference atomicity is likely to be easy on any ... memory barrier (eg a lock or volatile read/write) involved, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Thread safety and atomic assignment (again)
    ... By searching the web I found lots of references about the below question. ... Lea or Bloch) about it. ... the lack of volatile may cause setValues in thread to not be ... Doug Lea also asserts on p.93 that "atomicity extends to volatilie long and ...
    (comp.lang.java.programmer)