【发布时间】:2021-08-30 06:28:30
【问题描述】:
以下代码在数组的索引上使用 lock_cmpxchg 获取互斥锁,然后两个线程写入和读取相同的索引,但线程清理程序仍然说存在数据竞争。我怎么能告诉他线程之间有一个锁,因为它似乎没有检测到它。
aquire_mutex(bool* lock_ptr)
{
retval = _lock_cmpxchg_8bit(0, 1, lock_ptr); //lock_cmpxchg implemented in inline assembly
return (retval == 0) ? 1: 0;
}
foo()
{
if (aquire_mutex(global_lock[index])!= 1)
{
return error;
}
uint x = array[index];
...
array[index] = random_value;
}
流程是:
许多线程使用不同的索引或相同的索引运行,如果两个线程具有相同的索引,则会出现唯一的数据竞争,但它有一个锁。
但是线程清理程序警告线程 1 有一个读取行 uint x = array[index]; 并且有一个写入行 array[index] = random_value ;
我不确定它为什么会检测到数据竞争,感谢您的帮助!!
【问题讨论】:
-
您是否尝试过打开一些默认禁用的runtime options?我不知道它是否有帮助,但我会尝试运行:
TSAN_OPTIONS="force_seq_cst_atomics=1" ./your_program -
@TedLyngmo 谢谢,我应该在哪里写这行?因为我得到 TSAN_OPTIONS=history_size=7 force_seq_cst_atomics=1: Command not found.
-
这取决于你的外壳。我的建议适用于
bash。如果您使用不同的 shell,请尝试先设置此环境变量,然后单独运行命令。 -
根据
_lock_cmpxchg_8bit的实现方式,它可能对编译器不透明。您可能想显示它的源代码,并可能重写它以使用编译器内在函数。
标签: c thread-sanitizer