views:

117

answers:

4

Possible Duplicate:
Do I need to use locking with integers in c++ threads

Do critical sections inside trivial int accessors actually do anything useful?

int GetFoo()
{
   CriticalSection(crit_id);
   return foo;
}

void SetFoo(int value)
{
   CriticalSection(crit_id);
   foo = value;
}

Is it possible for two threads to be attempting to read and write foo simultaneously? I'd have thought 'no' unless integers are written byte-at-a-time, in which case I can see the use. But I'd have though modern cpus would read/write integers in a single atomic action...

A: 

AFAIK, No high level operation is atomic by default.

To write an integer the cpu has to calculate its physical address in memory, that requires some low level operations. You can be kicked out of the cpu at any time in the middle.

Maybe some languages offers you that posibility, but in general, popular languages (such as C++) don't. It's your responsability to create and maintain critical sections.

Some languages such as Java, does the dirty job for you, just adding synchronized as a key word when defining a function.

Here you have an example of how to create a critical section in C++ http://www.codeproject.com/KB/threads/cppsyncstm.aspx

pakore
+2  A: 

It depends on your arch as far as I know. Some systems reading/writing native width integers are atomic, on others no.

You should probably investigate the atomic intrinsics that the popular compilers offer.

Something like this for gcc:

__sync_lock_test_and_set(&foo, value);

This will set foo to value atomically (it'll also return the old value, but you can ignore that). There are many options for thread safety though.

Evan Teran
+1  A: 

As long as you are using memory aligned native word length integers, reads are atomic and can be done without locking but writes can give rise to race condition and therefore has to be locked. In case variable is not memory aligned, it can give rise to inconsistency in multi core/ multi cpu environment.

Rohit
A: 

AFAIK anything accessing the registers is not thread safe. I'm 95% positive incrementing a counter asynchronously with a ++ operator, for example, on a Pentium architecture is not thread safe.

Stefan Valianu