Non locking ::fwrite if possible (SPDLOG_FWRITE_UNLOCKED defined) or use the regular locking fwrite

This commit is contained in:
gabime
2024-11-30 15:46:06 +02:00
parent 551860d079
commit e26e3692d1
8 changed files with 76 additions and 6 deletions

View File

@@ -93,7 +93,7 @@ void file_helper::write(const memory_buf_t &buf) const {
if (fd_ == nullptr) return;
const size_t msg_size = buf.size();
const auto *data = buf.data();
if (std::fwrite(data, 1, msg_size, fd_) != msg_size) {
if (!os::fwrite_bytes(data, msg_size, fd_)) {
throw_spdlog_ex("Failed writing to file " + os::filename_to_str(filename_), errno);
}
}

View File

@@ -326,6 +326,17 @@ std::string getenv(const char *field) {
// Return true on success
bool fsync(FILE *fp) { return ::fsync(fileno(fp)) == 0; }
// Non locking ::fwrite if possible (SPDLOG_FWRITE_UNLOCKED defined) or use the regular locking fwrite
bool fwrite_bytes(const void *ptr, const size_t n_bytes, FILE *fp)
{
#if defined(SPDLOG_FWRITE_UNLOCKED)
return ::fwrite_unlocked(ptr, 1, n_bytes, fp) == n_bytes;
#else
return std::fwrite(ptr, 1, n_bytes, fp) == n_bytes;
#endif
}
} // namespace os
} // namespace details
} // namespace spdlog

View File

@@ -304,6 +304,15 @@ std::string getenv(const char *field) {
// Return true on success
bool fsync(FILE *fp) { return FlushFileBuffers(reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(fp)))) != 0; }
// Non locking fwrite if possible (SPDLOG_FWRITE_UNLOCKED defined) or use the regular locking fwrite
bool fwrite_bytes(const void *ptr, const size_t n_bytes, FILE *fp)
{
#if defined(SPDLOG_FWRITE_UNLOCKED)
return _fwrite_nolock(ptr, 1, n_bytes, fp) == n_bytes;
#else
return std::fwrite(ptr, 1, n_bytes, fp) == n_bytes;
#endif
}
} // namespace os
} // namespace details
} // namespace spdlog