开发者

Is a Critical Section around an integer getter and setter redundant? [duplicate]

开发者 https://www.devze.com 2023-01-03 15:58 出处:网络
This question already has answers he开发者_JS百科re: Closed 12 years ago. Possible Duplicate: Do I need to use locking with integers in c++ threads
This question already has answers he开发者_JS百科re: Closed 12 years ago.

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...


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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消