Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Don't access variable ouside of the critical section.
authorArnaud Giersch <arnaud.giersch@univ-fcomte.fr>
Thu, 23 Feb 2023 12:53:15 +0000 (13:53 +0100)
committerArnaud Giersch <arnaud.giersch@univ-fcomte.fr>
Thu, 23 Feb 2023 15:08:18 +0000 (16:08 +0100)
TSan warned about a data race there.
Also use a std::scoped_lock to handle the mutexi (Sonar).

src/xbt/dict.cpp

index 3d8703f..e733dad 100644 (file)
@@ -33,15 +33,12 @@ static void xbt_dict_postexit()
 }
 static void xbt_dict_preinit()
 {
-  if (dict_elm_mallocator == nullptr) {
-    static std::mutex init_mutex;
-    init_mutex.lock();
-    if (dict_elm_mallocator == nullptr) { // Just in case someone initialized it in between
-      dict_elm_mallocator =
-          xbt_mallocator_new(256, dict_elm_mallocator_new_f, dict_elm_mallocator_free_f, dict_elm_mallocator_reset_f);
-      atexit(xbt_dict_postexit);
-    }
-    init_mutex.unlock();
+  static std::mutex init_mutex;
+  const std::scoped_lock lock(init_mutex);
+  if (dict_elm_mallocator == nullptr) { // Just in case someone initialized it in between
+    dict_elm_mallocator =
+        xbt_mallocator_new(256, dict_elm_mallocator_new_f, dict_elm_mallocator_free_f, dict_elm_mallocator_reset_f);
+    atexit(xbt_dict_postexit);
   }
 }