64-bit integers and thread-safety

Apr 30, 2009 at 12:10am
I know reading and writing 32-bit integers while in 32-bit mode is safe because it can be done in a single clock (ignoring memory latency). I would assume this is not the case for 64-bit integers, since they don't fit in a single register, and I'm guessing the data bus is not wide enough either.

So, is reading and writing 64-bit integers (and all data types larger than 32 bits, for that matter) thread-safe in 32-bit mode?
Apr 30, 2009 at 7:05am
writing a 32 bit integer is also not atomic operation.. leave 64 bit...

there are certain win32 apis for atomic operations..i can tell if you want..
on unix i have to search ...
Apr 30, 2009 at 7:15am
Apr 30, 2009 at 12:21pm
http://software.intel.com/en-us/forums/watercooler-catchall/topic/48395/

Okay, I just read up a little on this. Atomicity depends on the alignment of the variable:
Case A:
|00 VA RI AB|
|LE 00 00 00|
Not atomic.

Case B:
|VA RI AB LE|
Atomic on a single core 32-bit processor without Hyper-Threading.

Makes sense.
What about multi-core or hyper-threaded processors for case B?
Last edited on Apr 30, 2009 at 12:22pm
Apr 30, 2009 at 4:24pm
hmm... does that mean 32 bit variables or even 64bit ones will have atomic operation??
because the variables are aligned.

then whats the use of these interlocked increment/decrement functions??
Apr 30, 2009 at 4:36pm
A 64-bit variable write may be atomic in 64-bit mode, just like a 32-bit variable write may be atomic in 32-bit mode.

I imagine InterlockedIncrement() uses a special instruction that guarantees the increment will be atomic, regardless of alignment.
Last edited on Apr 30, 2009 at 5:41pm
Apr 30, 2009 at 5:37pm
i agree..

but an int type will always be aligned to word boundaries.. if i am correct..
Apr 30, 2009 at 5:45pm
How do you mean? Like |VA RI AB LE| and |00 00 VA RI||AB LE 00 00|?
Not necessarily. What about this?
1
2
3
4
struct A{
    char a;
    int b;
};

Although I can't remember ATM if the compiler adds padding between members or only at the end. I'm guessing at the end, otherwise it would be too wasteful.
Last edited on Apr 30, 2009 at 5:45pm
Apr 30, 2009 at 6:53pm
The compiler adds padding by default, however some compilers allow you to turn it off.

FWIW, some architectures don't allow misaligned accesses while others do.
May 1, 2009 at 4:22am
thats what i was saying.. a class or a variable or struct will be aligned and mostly all the compilers do that.. so chances are that the operations will be atomic.. but only in case of 32/64 bit values as Helios said..


anyway.. there is nothing to discuss on this topic i think.. we all are saying the same thing differently.. :)
Topic archived. No new replies allowed.