-fsanitize=thread
编译时,添加参数-fsanitize=thread -g
,可以运行态检查数据竞态问题,包括:
- 数据竞态
- 死锁
- 锁、条件变量错误使用
check_tsan
开源库 yalantinglibs有段检查编译器是否支持 fsanitize 编译参数的宏,挺有意思,摘录下:
代码如下(以下宏代码,问下 AI 就懂其语法和工作方式):
macro(check_tsan _RESULT)
include(CheckCXXSourceRuns)
set(CMAKE_REQUIRED_FLAGS "-fsanitize=thread")
check_cxx_source_runs(
[====[
int main()
{
return 0;
}
]====]
${_RESULT}
)
unset(CMAKE_REQUIRED_FLAGS)
endmacro()
该宏按以下方式使用:
if(ENABLE_SANITIZER AND NOT MSVC)
if (ENABLE_TSAN)
## thread sanitizer
check_tsan(HAS_TSAN)
if(HAS_TSAN)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread")
else()
message(WARNING "thread sanitizer is no supported with current tool-chains")
endif()
endif()
endif()
参考
- https://zhuanlan.zhihu.com/p/691182407