From 8493b955cc845b0f9587998f79c83dce384a4b98 Mon Sep 17 00:00:00 2001 From: Ilya Matveev Date: Mon, 28 Mar 2022 14:23:23 +0700 Subject: [PATCH] [K/N][runtime] Add a lock on finalizer thread creation The finalizer thread can be created from the GC thread or from any application thread during runtime shutdown. This may cause a rare race when the GC starts the finalizer thread during runtime shutdown. In this case two finalizer threads may be created and the app will crash on attempt to assign the finalizerThread_ field in FinalizerProcessor. --- kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.cpp | 2 ++ kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.hpp | 2 ++ 2 files changed, 4 insertions(+) diff --git a/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.cpp b/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.cpp index ce678319e71..74f09cb3257 100644 --- a/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.cpp +++ b/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.cpp @@ -9,7 +9,9 @@ void kotlin::gc::FinalizerProcessor::StartFinalizerThreadIfNone() noexcept { + std::unique_lock guard(threadCreatingMutex_); if (finalizerThread_.joinable()) return; + finalizerThread_ = ScopedThread(ScopedThread::attributes().name("GC finalizer processor"), [this] { Kotlin_initRuntimeIfNeeded(); { diff --git a/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.hpp b/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.hpp index 85cfca0e89c..f20acfc1b59 100644 --- a/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.hpp +++ b/kotlin-native/runtime/src/gc/cms/cpp/FinalizerProcessor.hpp @@ -38,6 +38,8 @@ private: std::mutex initializedMutex_; std::condition_variable initializedCondVar_; bool initialized_ = false; + + std::mutex threadCreatingMutex_; }; } // namespace kotlin::gc