【发布时间】:2016-07-07 17:28:10
【问题描述】:
我使用 asm 编写了 atomic_inc 来增加一个整数,它实际上用于引用共享对象的计数。 gcc 4.8.2 -fsanitize=thread 报告数据竞争,我终于发现这很可能是由我的 atomic_inc 引起的。我不相信我的代码存在与数据竞争有关的错误,这是 tsan 的误报吗?
static inline int atomic_add(volatile int *count, int add) {
__asm__ __volatile__(
"lock xadd %0, (%1);"
: "=a"(add)
: "r"(count), "a"(add)
: "memory"
);
return add;
}
void MyClass::Ref() {
// std::unique_lock<std::mutex> lock(s_ref);
atomic_add(&_refs, 1);
}
void MyClass::Unref() {
// std::unique_lock<std::mutex> lock(s_ref);
int n = atomic_add(&_refs, -1) - 1;
// lock.unlock();
assert(n >= 0);
if (n <= 0) {
delete this;
}
}
【问题讨论】:
-
除了下面(到目前为止)2 个很好的答案之外,您的 asm 也是不正确的。此代码更改仅输入参数(计数)的值。如果你必须使用 asm,也许像
asm("lock xadd %[add], %[count]" : [add] "+r"(add), [count] "+m"(count) : : "memory", "cc");?
标签: c++ linux multithreading locking