Improve log guard.

This commit is contained in:
levlam 2022-11-18 14:33:23 +03:00
parent f8e2af3f59
commit 47aa5b51c7
4 changed files with 31 additions and 8 deletions

View File

@ -61,8 +61,7 @@ Status AsyncFileLog::init(string path, int64 rotate_threshold, bool redirect_std
}
while (!slice.empty()) {
if (redirect_stderr) {
auto &guard = get_log_guard();
while (guard.load() != 0) {
while (has_log_guard()) {
// spin
}
}

View File

@ -83,8 +83,7 @@ void FileLog::do_append(int log_level, CSlice slice) {
}
while (!slice.empty()) {
if (redirect_stderr_) {
auto &guard = get_log_guard();
while (guard.load() != 0) {
while (has_log_guard()) {
// spin
}
}

View File

@ -250,9 +250,24 @@ void process_fatal_error(CSlice message) {
std::abort();
}
std::atomic<uint32> &get_log_guard() {
static std::atomic<uint32> log_guard;
return log_guard;
static std::atomic<uint32> log_guard;
LogGuard::LogGuard() {
uint32 expected = 0;
while (!log_guard.compare_exchange_strong(expected, 1, std::memory_order_relaxed, std::memory_order_relaxed)) {
// spin
CHECK(expected == 1);
expected = 0;
}
}
LogGuard::~LogGuard() {
CHECK(log_guard.load(std::memory_order_relaxed) == 1);
log_guard.store(0, std::memory_order_relaxed);
}
bool has_log_guard() {
return log_guard.load(std::memory_order_relaxed) == 1;
}
namespace {

View File

@ -221,7 +221,17 @@ class Logger {
int log_level_;
};
std::atomic<uint32> &get_log_guard();
class LogGuard {
public:
LogGuard();
LogGuard(const LogGuard &) = delete;
LogGuard &operator=(const LogGuard &) = delete;
LogGuard(LogGuard &&) = delete;
LogGuard &operator=(LogGuard &&) = delete;
~LogGuard();
};
bool has_log_guard();
class ScopedDisableLog {
public: