C++线程安全分析
除了通过code review或者test来检测线程安全,有没有其它更好的办法?
答案是存在的,通过clang即可以进行这种检测,编译器对存在的线程安全问题会给出警告。
这种分析方法由Google开发,已经被Google大规模应用,参考
https://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/42958.pdf
示例example.cpp:
#include "mutex.h"
class BankAccount {
private:
Mutex mu;
int balance GUARDED_BY(mu);
void depositImpl(int amount) {
balance += amount; // WARNING! Cannot write balance without locking mu.
}
void withdrawImpl(int amount) REQUIRES(mu) {
balance -= amount; // OK. Caller must have locked mu.
}
public:
void withdraw(int amount) {
mu.Lock();
withdrawImpl(amount); // OK. We've locked mu.
} // WARNING! Failed to unlock mu.
void transferFrom(BankAccount& b, int amount) {
mu.Lock();
b.withdrawImpl(amount); // WARNING! Calling withdrawImpl() requires locking b.mu.
depositImpl(amount); // OK. depositImpl() has no requirements.
mu.Unlock();
}
};
通过然后指定-Wthread-safety编译选项,即clang -c -Wthread-safety example.cpp命令编译即可以给出警告。
更多细节可以参考: https://clang.llvm.org/docs/ThreadSafetyAnalysis.html