Are C++ Reads and Writes of an int Atomic?

2019-01-03 02:28发布

I have two threads, one updating an int and one reading it. This is a statistic value where the order of the reads and writes is irrelevant.

My question is, do I need to synchronize access to this multi-byte value anyway? Or, put another way, can part of the write be complete and get interrupted, and then the read happen.

For example, think of a value = 0x0000FFFF that gets incremented value of 0x00010000.

Is there a time where the value looks like 0x0001FFFF that I should be worried about? Certainly the larger the type, the more possible something like this to happen.

I've always synchronized these types of accesses, but was curious what the community thinks.

15条回答
forever°为你锁心
2楼-- · 2019-01-03 02:41

Yes, you need to synchronize accesses. In C++0x it will be a data race, and undefined behaviour. With POSIX threads it's already undefined behaviour.

In practice, you might get bad values if the data type is larger than the native word size. Also, another thread might never see the value written due to optimizations moving the read and/or write.

查看更多
该账号已被封号
3楼-- · 2019-01-03 02:42

No, they aren't (or at least you can't assume they are). Having said that, there are some tricks to do this atomically, but they typically aren't portable (see Compare-and-swap).

查看更多
Rolldiameter
4楼-- · 2019-01-03 02:42

Lets take this example

int x;
x++;
x=x+5;

The first statement is assumed to be atomic because it translates to a single INC assembly directive that takes a single CPU cycle. However, the second assignment requires several operations so it's clearly not an atomic operation.

Another e.g,

x=5;

Again, you have to disassemble the code to see what exactly happens here.

查看更多
三岁会撩人
5楼-- · 2019-01-03 02:44

IF you're reading/writing 4-byte value AND it is DWORD-aligned in memory AND you're running on the I32 architecture, THEN reads and writes are atomic.

查看更多
欢心
6楼-- · 2019-01-03 02:46

Asside from the cache issue mentioned above...

If you port the code to a processor with a smaller register size it will not be atomic anymore.

IMO, threading issues are too thorny to risk it.

查看更多
【Aperson】
7楼-- · 2019-01-03 02:47

To echo what everyone said upstairs, the language pre-C++0x cannot guarantee anything about shared memory access from multiple threads. Any guarantees would be up to the compiler.

查看更多
登录 后发表回答