Open anarthal opened 2 days ago
FWIW: The issue seems to be solely in weak_ptr
as this example fails in the same way. I also added a define check to verify the atomic is actually used, see also https://godbolt.org/z/7ara7MP5f:
#include <memory>
#include <thread>
#include <vector>
#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
// OK
#else
#error "FAIL"
#endif
void perform()
{
// Setup
std::weak_ptr<int> w_outer = std::shared_ptr<int>(new int);
std::vector<std::thread> threads;
for (int i = 0; i < 16; ++i)
{
threads.emplace_back([w = w_outer]() mutable {
std::this_thread::yield();
w.reset();
});
}
w_outer.reset();
for (auto& t : threads)
t.join();
}
int main()
{
for (int i = 0; i < 10000; ++i)
perform();
}
I've been running several tests involving sharing
std::shared_ptr
andstd::weak_ptr
objects under thread sanitizer. I've been getting a bunch of race condition reports. The code under test shares a single, constant value allocated usingstd::make_shared
by copying a bunch ofstd::shared_ptr
andstd::weak_ptr
objects to several threads.I've been able to isolate a minimum reproducible example with clang-18 and libc++-18 packages under Ubuntu 24.04. Please find a full Dockerfile containing self-contained instructions on how to reproduce the issue at the bottom of this message.
Interestingly, the race condition is only reported when combining
std::shared_ptr
andstd::weak_ptr
objects. Commenting the branch creating the weak pointers makes the race condition disappear.Please let me know if I can help anyhow.
Dockerfile for reproduction:
TSAN report: