mimalloc icon indicating copy to clipboard operation
mimalloc copied to clipboard

_Atomic in C++

Open tmcdaniel-aspyr opened this issue 1 month ago • 1 comments

When built as C++, _Atomic in mimalloc is defined as std::atomic. For Clang, mi_process_attach() in prim.c is declared so it runs before static ctors. The result is that any file level atomic values that happen be set during mi_process_attach() are then stomped by the std::atomic ctors, which zero init their values. For example, in page-map.c:

static _Atomic(mi_bfield_t)  mi_page_map_commit;

tmcdaniel-aspyr avatar Oct 31 '25 23:10 tmcdaniel-aspyr

I tried to experiment a bit with Compiler Explorer; this code

static std::atomic<uint64_t> cxx_atomic;
static _Atomic uint64_t c_atomic;

...when compiled with clang doesn't actually create static initialization code for either variable!

Though, while your mileage seems to vary here, perhaps this can serve as an inspiration:

  • Perhaps it's possible to have clang "optimize away" the ctors of std::atomic<> static variables?
  • If clang understands C _Atomic when compiling C++ code, perhaps using that for all affected static variables may also avoid having ctors for those.

res2k avatar Nov 01 '25 02:11 res2k