Clang ThreadSanitizer:解锁一个未锁定的互斥体,一个原子正在创建数据竞争

Clang ThreadSanitizer: unlock of an unlocked mutex, and an atomic is creating a data-race

我正在使用 ThreadSanitizer 进行线程分析,我收到一条警告,这让我对互斥量的工作原理的理解非常非常混乱。我在 Debian Stretch 上使用 gcc 6.3。

在一个 class 中,在一个线程中,我有:

auto MyPtr = std::make_shared<MyClass>(...);

在另一个线程调用的另一个地方,我有:

if(MyPtr.get()) {...}

ThreadSanitizer 警告我竞争条件,这很好。所以我通过以下方式解决了这个问题:

std::unique_lock<decltype(MyMutex)> lg(MyMutex); //MyMutex is std::mutex
auto MyPtr = std::make_shared<...>(...);
lg.unlock();

还有另一个地方:

std::unique_lock<decltype(MyMutex)> lg(MyMutex);
if(MyPtr.get()) {...}
// mutex unlocks at the end of the function, which is like after another if-condition.

现在数据争用消失了,ThreadSanitizer 说正在解锁 Mutex "twice"...

WARNING: ThreadSanitizer: unlock of an unlocked mutex (or by a wrong thread)

它指向 unlock() 调用 + 另一个函数的结尾。

一个互斥体怎么会被解锁两次?有人能解释一下吗?

现在因为这让我很头疼,所以我决定改为这样做:

std::shared_ptr<MyClass> MyPtr; //in the class definition
std::atomic_store(&MyPtr, std::make_shared<MyClass>(...));

现在我收到了数据争用投诉:

WARNING: ThreadSanitizer: data race

那我是不是用错了ThreadSanitizer?有人可以解释一下这是怎么回事吗?

我从来没有弄清楚互斥问题,但我能够通过使另一个负载成为原子来摆脱与原子的数据竞争:

if(std::atomic_load(&MyPtr).get()) {...}