# HG changeset patch # User Patric Stout # Date 2021-06-17 18:10:40 # Node ID 31eedcf7ade01f02ff5975a50a47c3c367a4126d # Parent 60c9c8536270458b83d84ea0b5256ea49ccbcc47 Fix: on startup, NewGRF scan could case race-condition (#9382) Creating a thread was not thread-safe. The irony. The video-driver has a function GameLoopPause() which first checks if the thread is the game-thread or not. For this it needs access to this->game_thread. This variable is set in StartNewThread(). However, due to timing, it is well possible GameLoopPause() is called from the thread well before this->game_thread is assigned. And so we have a race-condition! Simply solve this by preventing a thread to start till we are done with our bookkeeping. diff --git a/src/thread.h b/src/thread.h --- a/src/thread.h +++ b/src/thread.h @@ -14,6 +14,7 @@ #include "crashlog.h" #include #include +#include /** * Sleep on the current thread for a defined time. @@ -46,7 +47,17 @@ inline bool StartNewThread(std::thread * { #ifndef NO_THREADS try { + static std::mutex thread_startup_mutex; + std::lock_guard lock(thread_startup_mutex); + std::thread t([] (const char *name, TFn&& F, TArgs&&... A) { + /* Delay starting the thread till the main thread is finished + * with the administration. This prevent race-conditions on + * startup. */ + { + std::lock_guard lock(thread_startup_mutex); + } + SetCurrentThreadName(name); CrashLog::InitThread(); try {