Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the c++ operator |= atomic with a multicore processor?

I am currently in debate with another developer who assures me that the following c++ statement is atomic:

x |= 0x1; // x is shared by multiple threads

Compiled with VC++11 in release mode this generates the following assemby:

01121270  or          dword ptr ds:[1124430h],1

The other developer says that the bit operations are atomic and therefore thread safe. My experience with an intel i7 processor says otherwise.

I thought that with a multicore processor, any shared memory write is unsafe because of the individual processor caches. But having done more research it seems as though the x86 processors provide some guarantees in relation to the order of memory operations between processors/cores which suggest that it should be safe... again, this doesn't seem to be the case in my experience.

Since I don't have authoritative knowledge of these kinds of things it's difficult for me to put my case or even be confident that I'm right.

like image 286
Robert Smith Avatar asked Feb 11 '23 16:02

Robert Smith


1 Answers

No, it's definitely not guaranteed to be atomic. Whether it's implemented using an uniterruptible instruction (sequence) or not is up to the compiler and platform. But from the point of view of the standard, it's not atomic; so if one thread perfroms x |= 0x1; and another thread accesses x without a synchronisation point in between, it's Undefined Behaviour (a data race).

Supporting quotes from C++11:

1.10/5:

The library defines a number of atomic operations (Clause 29) and operations on mutexes (Clause 30) that are specially identified as synchronization operations. ...

Clause 29 introduces std::atomic and related functions. It does not specify fundamental types as atomic.

1.10/21:

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior. ...

like image 93
Angew is no longer proud of SO Avatar answered Feb 24 '23 16:02

Angew is no longer proud of SO