我的自旋锁实现如下所示,我认为它不会引起任何数据争用,但是当我使用-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:



因此,它不知道atomic_swap()应该做什么,并且不知道在ThreadSanitizer currently doesn't support memory fences之上。

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

10-11 22:20