Look at the context of my question:

Memory blocks need protecting just the same as variables - for the exact
same reasons - after all, a variable is just a small memory block.

There's only one exception to it, which is when the memory holds a variable which can be written with a single instruction (like a 4 byte integer) and you don't care if the reader thread gets an outdated value from time to time. In that case, I'd simply declare the variable as volatile, and access it as usual in the code.

I'm not sure about that. If this were true, why ::InterlockedIncrement( )?


The InterlockedIncrement( ) function does an atomic copy, so it's impossible for the reader thread to get an outdated value. But simply declaring the variable as volatile doesn't prevent that from happening. The only thing it does is ensuring the compiler doesn't cache the variable's values in registers and fetch it from the main memory each time it's being accessed.

My point is that even with a 4-byte integer shared between threads you can't be guaranteed a correct value unless you use synchronization. IINM the Interlocked...( ) functions either do a full read or a full write but are guaranteed to not do half and get pre-empted. Check out this statement from the msdn:


<quote>
The InterlockedIncrement function increments (increases by one) the value of the specified 32-bit variable and checks the resulting value. The function prevents more than one thread from using the same variable simultaneously.
</quote>


Why would you need to worry about more than one thread accessing a 4 byte var? Two reasons, the half-writes we have discussed, and two threads thinking they will increment the var and it only gets incremented once.

Even if you are incrementing a var it must be read into the processor, incremented then wrote back to memory. That operation can be preempted unless you use sync like Interlocked...( ).

To me the very existence of InterlockedIncrement( ) shows that the sharing of even a 4 byte var must be synchronized unless the only way it is ever used is "read". As soon as you get one thread changing the val you have to use InterlockedIncrement( ) to prevent out-of-sync problems.

/dev


_______________________________________________ msvc mailing list [email protected] See http://beginthread.com/mailman/listinfo/msvc_beginthread.com for subscription changes, and list archive.

Reply via email to