microsoft / STL

MSVC's implementation of the C++ Standard Library.
Other
9.88k stars 1.45k forks source link

`<atomic>`: On x64, `atomic_ref::is_lock_free()` incorrectly returns `true` when it shouldn't #4728

Closed StephanTLavavej closed 1 day ago

StephanTLavavej commented 1 week ago

Repros with VS 2022 17.11 Preview 2 x64:

C:\Temp>type meow.cpp
#include <atomic>
#include <print>
using namespace std;

struct Large {
    char str[100]{};
};

int main() {
    Large lg{};
    atomic_ref<Large> atom_ref{lg};
    println("atomic_ref<Large> is_lock_free(): {}", atom_ref.is_lock_free());
    atom_ref.store(Large{"cute fluffy kittens"});
    println("lg.str: {}", lg.str);
}
C:\Temp>cl /EHsc /nologo /W4 /std:c++latest /MTd /Od /Zi /Fdmeow.pdb meow.cpp
meow.cpp

C:\Temp>meow
atomic_ref<Large> is_lock_free(): true
lg.str: cute fluffy kittens

atomic_ref<Large>::store() definitely takes a lock:

https://github.com/microsoft/STL/blob/e36ee6c2b9bc6f5b1f70776c18cf5d3a93a69798/stl/inc/atomic#L630-L635

atomic_ref::is_lock_free() is bogus because:

https://github.com/microsoft/STL/blob/e36ee6c2b9bc6f5b1f70776c18cf5d3a93a69798/stl/inc/atomic#L2367-L2376

This meant to say: "If we're always lock-free then true, otherwise we have to be potentially lock-free and actually have cmpxchg16b."

I have a fix.