Logger: improve thread safety.

This commit is contained in:
Guillaume Jacquemin 2022-04-25 08:24:56 +02:00
parent 929e0c73ee
commit 874dd9bd4c
2 changed files with 33 additions and 13 deletions

View file

@ -82,8 +82,6 @@ initialise() {
void void
addEntry(EntryType type, StringView message) { addEntry(EntryType type, StringView message) {
_logMutex.lock();
auto time = std::time(nullptr); auto time = std::time(nullptr);
static char formatted_time[20] = {'\0'}; static char formatted_time[20] = {'\0'};
@ -106,20 +104,28 @@ addEntry(EntryType type, StringView message) {
} << entry; } << entry;
arrayAppend(_entries, std::move(entry)); arrayAppend(_entries, std::move(entry));
_logMutex.unlock();
} }
ArrayView<const LogEntry> ArrayView<const LogEntry>
entries() { entries() {
if(!_logMutex.try_lock()) {
return nullptr;
}
_logMutex.unlock();
return _entries; return _entries;
} }
void
lockMutex() {
_logMutex.lock();
}
void
unlockMutex() {
_logMutex.unlock();
}
bool
tryLockMutex() {
return _logMutex.try_lock();
}
} // Logger } // Logger
} // MassBuilderSaveTool } // MassBuilderSaveTool

View file

@ -48,11 +48,25 @@ void addEntry(EntryType type, StringView message);
auto entries() -> ArrayView<const LogEntry>; auto entries() -> ArrayView<const LogEntry>;
void lockMutex();
void unlockMutex();
bool tryLockMutex();
} // Logger } // Logger
} // MassBuilderSaveTool } // MassBuilderSaveTool
#define LOG_INFO(message) MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Info, message) #define LOG_INFO(message) MassBuilderSaveTool::Logger::lockMutex(); \
#define LOG_SUCCESS(message) MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Success, message) MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Info, message); \
#define LOG_WARNING(message) MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Warning, message) MassBuilderSaveTool::Logger::unlockMutex();
#define LOG_ERROR(message) MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Error, message) #define LOG_SUCCESS(message) MassBuilderSaveTool::Logger::lockMutex(); \
MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Success, message); \
MassBuilderSaveTool::Logger::unlockMutex();
#define LOG_WARNING(message) MassBuilderSaveTool::Logger::lockMutex(); \
MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Warning, message); \
MassBuilderSaveTool::Logger::unlockMutex();
#define LOG_ERROR(message) MassBuilderSaveTool::Logger::lockMutex(); \
MassBuilderSaveTool::Logger::addEntry(MassBuilderSaveTool::Logger::EntryType::Error, message); \
MassBuilderSaveTool::Logger::unlockMutex();