简体   繁体   English

使用C ++标准库进行线程安全性分析

[英]Clang thread safety analysis with C++ standard library

This describes how static thread safety analysis can be done with annotations in C++: http://clang.llvm.org/docs/ThreadSafetyAnalysis.html 这描述了如何使用C ++中的注释完成静态线程安全性分析: http//clang.llvm.org/docs/ThreadSafetyAnalysis.html

How can I use this with standard types like std::mutex and std::lock_guard? 我如何使用标准类型,如std :: mutex和std :: lock_guard?

The example code of mutex.h annotates a custom interface. mutex.h的示例代码注释了自定义接口。 Do I have the type "Mutex" which is defined there and implement a class using std::mutex with the annotated methods or does Clang bring annotated types somehow? 我是否在那里定义了“Mutex”类型并使用带注释方法的std :: mutex实现了一个类,或者Clang是否以某种方式引入了带注释的类型?

Implement the interface described in the supplied mutex.h file, and use the std::mutex class to do so. 实现提供的mutex.h文件中描述的接口,并使用std :: mutex类来执行此操作。 Ie here is a half-finished implementation: 即这是一个半完成的实现:

Minor change to mutex.h file to include a std::mutex object mutex.h文件进行微小更改以包含std :: mutex对象

class CAPABILITY("mutex") Mutex {
private:
  std::mutex std_mutex;
public:
  // Acquire/lock this mutex exclusively.  Only one thread can have exclusive
  // access at any one time.  Write operations to guarded data require an
  // exclusive lock.

Then implement the rest in mutex.cpp 然后在mutex.cpp中实现其余部分

#include "mutex.h"

void Mutex::Lock(){
  this->std_mutex.lock();
}

void Mutex::Unlock(){
  this->std_mutex.unlock();
}

bool Mutex::TryLock(){
  return this->std_mutex.try_lock();
}

In recent versions of clang, you probably don't have to wrap std::mutex anymore, because the thread-safety annotations are included since March 15, 2016 . 在clang的最新版本中,您可能不再需要包装std :: mutex,因为自2016年3月15日起包含了线程安全注释。

This adds clang thread safety annotations to std::mutex and std::lock_guard so code using these types can use these types directly instead of having to wrap the types to provide annotations. 这为std :: mutex和std :: lock_guard添加了clang线程安全注释,因此使用这些类型的代码可以直接使用这些类型,而不必包装类型以提供注释。 These checks when enabled by -Wthread-safety provide simple but useful static checking to detect potential race conditions. 通过-Wthread-safety启用时,这些检查提供了简单但有用的静态检查,以检测潜在的竞争条件。

See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html for details. 有关详细信息,请参见http://clang.llvm.org/docs/ThreadSafetyAnalysis.html

So simply having -Wthread-safety should be enough. 因此,简单地使用-Wthread-safety就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM