https://bugs.llvm.org/show_bug.cgi?id=43813

            Bug ID: 43813
           Summary: Insufficient locking in
                    std::atomic_compare_exchange_strong for
                    std::shared_ptr
           Product: libc++
           Version: 9.0
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: All Bugs
          Assignee: unassignedclangb...@nondot.org
          Reporter: lahav.sch.l...@gmail.com
                CC: llvm-bugs@lists.llvm.org, mclow.li...@gmail.com

Hi,

The implementation of 'std::atomic_compare_exchange_strong(shared_ptr* p,
shared_ptr* v, shared_ptr w)' only locks the mutex related to 'p', but not the
one for 'v' as well.

This means the following code (Which should have no race conditions):


#include <memory>
#include <atomic>
#include <unistd.h>
#include <pthread.h>

std::shared_ptr<int> g_p;

static void* thread_run(void*) {
    auto w = std::make_shared<int>();

    while (true) {
        auto p = std::make_shared<int>();

        std::atomic_compare_exchange_strong(&p, &g_p, w);
    }

    return nullptr;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, nullptr, thread_run, nullptr);

    auto w = std::make_shared<int>();

    while(true) {        
        std::atomic_store(&g_p, w);
    }
}


may attempt to access the same 'g_p' instance from multiple threads - The main
thread (Via std::atomic_store()) will properly lock the matching mutex, but the
2nd thread will not, causing a race condition.

I believe the mutex for 'v' should be locked as well, with special care as to
not introduce a deadlock now that 2 mutexes are being locked.

-- 
You are receiving this mail because:
You are on the CC list for the bug.
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to