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