From 8268c61b9f841c7e7e900a90223a43b2126fadbb Mon Sep 17 00:00:00 2001 From: sfan5 Date: Wed, 5 Jun 2024 22:58:33 +0200 Subject: [PATCH] Make safeWriteToFile safe for thread-concurrent use --- src/filesys.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/filesys.cpp b/src/filesys.cpp index a61f7f0aa..26cdaba07 100644 --- a/src/filesys.cpp +++ b/src/filesys.cpp @@ -25,6 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include +#include #include "log.h" #include "config.h" #include "porting.h" @@ -854,10 +855,12 @@ const char *GetFilenameFromPath(const char *path) return filename ? filename + 1 : path; } +// Note: this is not safe if two MT processes try this at the same time (FIXME?) bool safeWriteToFile(const std::string &path, std::string_view content) { - // Note: this is not safe if two MT processes try this at the same time (FIXME?) - const std::string tmp_file = path + ".~mt"; + // Prevent two threads from writing to the same temporary file + static std::atomic g_file_counter; + const std::string tmp_file = path + ".~mt" + itos(g_file_counter.fetch_add(1)); // Write data to a temporary file std::string write_error;