[llvm-bugs] [Bug 43813] New: Insufficient locking in std::atomic_compare_exchange_strong for std::shared_ptr

via llvm-bugs llvm-bugs at lists.llvm.org
Sat Oct 26 01:01:22 PDT 2019


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: unassignedclangbugs at nondot.org
          Reporter: lahav.sch.llvm at gmail.com
                CC: llvm-bugs at lists.llvm.org, mclow.lists at 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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20191026/f4d249cd/attachment-0001.html>


More information about the llvm-bugs mailing list