Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ThreadSanitizer: std::localtime() is not thread-safe. #4344

Merged
merged 9 commits into from
Mar 21, 2022
9 changes: 7 additions & 2 deletions dbms/src/Common/UnifiedLogPatternFormatter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ std::string UnifiedLogPatternFormatter::getTimestamp()
auto time_point = std::chrono::system_clock::now();
auto tt = std::chrono::system_clock::to_time_t(time_point);

std::tm * local_tm = std::localtime(&tt);
std::tm buf_tm;
std::tm * local_tm = localtime_r(&tt, &buf_tm);
JaySon-Huang marked this conversation as resolved.
Show resolved Hide resolved
if (unlikely(!local_tm))
return "1970/01/01 00:00:00.000 +00:00";
int year = local_tm->tm_year + 1900;
int month = local_tm->tm_mon + 1;
int day = local_tm->tm_mday;
Expand All @@ -125,7 +128,9 @@ std::string UnifiedLogPatternFormatter::getTimestamp()
auto offset_seconds = std::chrono::seconds(offset_value);
auto offset_tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds>(offset_seconds);
auto offset_tt = std::chrono::system_clock::to_time_t(offset_tp);
std::tm * offset_tm = std::gmtime(&offset_tt);
std::tm * offset_tm = gmtime_r(&offset_tt, &buf_tm);
if (unlikely(!offset_tm))
return fmt_buf.toString() + "+00:00";
if (zone_offset < 0)
fmt_buf.append("-");
else
Expand Down