c++ - ThreadSanitizer 说我的 spin_lock 有数据竞争,但是怎么办?

标签 c++ linux multithreading crash locking

我的自旋锁实现如下所示,我认为它不会导致任何数据竞争,但是当我使用 -fsanitize=thread 测试我的代码时,它报告 spin_unlock 有写数据竞争。怎么会这样?是误报吗?

#define barrier() asm volatile("": : :"memory")
#define cpu_relax() asm volatile("pause\n": : :"memory")

static inline void spin_lock(volatile int *lock) {
    while (1)
    {
        int i = 0;
        if (!atomic_swap(lock, EBUSY)) return;
        while (*lock) {
            i++;
            if (i == 4000) {
                i = 0;
                thread_yield();
            }
            cpu_relax();
        }
    }
}

static inline void spin_unlock(volatile int *lock) {
    barrier();
    *lock = 0;
}

atomic_swap 是一个函数:

static inline int atomic_swap(volatile void *lockword, int value) {
    unsigned long tmp;
    int result;
    __asm__ __volatile__ ("dmb" : : : "memory");
    __asm__ __volatile__("@ atomic_swap\n"
    "1: ldrex   %0, [%2]\n"
    "   strex   %1, %3, [%2]\n"
    "   teq %1, #0\n"
    "   bne 1b"
    : "=&r" (result), "=&r" (tmp)
    : "r" (lockword), "Ir" (value)
    : "cc");

    __asm__ __volatile__ ("dmb" : : : "memory");
    return result;
}

最佳答案

ThreadSanitizer 不知道您自己开发的 atomic_swap()barrier() 函数的语义。来自ThreadSanitizer FAQ :

Q: What synchronization primitives are supported? TSan supports pthread synchronization primitives, built-in compiler atomic operations (sync/atomic), C++ operations are supported with llvm libc++ (not very throughly [sic] tested, though).

所以它不知道 atomic_swap() 应该做什么,除此之外 ThreadSanitizer currently doesn't support memory fences .

关于c++ - ThreadSanitizer 说我的 spin_lock 有数据竞争,但是怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122580/

相关文章:

iphone - 在 objective-c 中使用 c++ 类

c++ - 我可以使用结构的 "browse"成员来简化 BDD 类的构建吗?

c++ - 在哪里可以找到 Windows 进程中已卸载模块的列表?

c++ - Linux jdk1.6.0_25 x64(64 位)中的可能回归

linux - 对于 GNU/Linux,附加到/bin/bash 中的 LD_LIBRARY_PATH

java - 三星 Galaxy S3 的 Linux 开发/部署

java - LibGDX:在另一个线程中创建新的 scene2d 对象?

c++ - 如何在c++中创建不同数量的线程?

java - 如何从另一个 java 类(意味着在 Controller 之外)更改 .fxml 文件的标签文本?

c++ - 对带有可变参数模板的 std::ref() 和 std::bind() 有点模糊