[PATCH] D109914: [Support] Attempt to fix deadlock in ThreadGroup

Alexandre Ganea via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Thu Sep 16 13:09:50 PDT 2021


aganea created this revision.
aganea added reviewers: stellaraccident, mehdi_amini, MaskRay.
Herald added subscribers: dexonsmith, hiraditya.
aganea requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

This is an attempt to fix the situation described by https://reviews.llvm.org/D104207#2826290 and PR41508.

See sequence of operations leading to the bug in https://reviews.llvm.org/D104207#3004689

We ensure that the Latch is completely "free" before decrementing the number of `TaskGroupInstances`.
Also, `std::condition_variable::notify_all()` is now called outside of the lock, to prevent spurious wakeup of the waiting threads, followed by going into wait state again, before ever checking the condition.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D109914

Files:
  llvm/include/llvm/Support/Parallel.h
  llvm/lib/Support/Parallel.cpp


Index: llvm/lib/Support/Parallel.cpp
===================================================================
--- llvm/lib/Support/Parallel.cpp
+++ llvm/lib/Support/Parallel.cpp
@@ -151,7 +151,10 @@
 // lock, only allow the first TaskGroup to run tasks parallelly. In the scenario
 // of nested parallel_for_each(), only the outermost one runs parallelly.
 TaskGroup::TaskGroup() : Parallel(TaskGroupInstances++ == 0) {}
-TaskGroup::~TaskGroup() { --TaskGroupInstances; }
+TaskGroup::~TaskGroup() {
+  L.sync();
+  --TaskGroupInstances;
+}
 
 void TaskGroup::spawn(std::function<void()> F) {
   if (Parallel) {
Index: llvm/include/llvm/Support/Parallel.h
===================================================================
--- llvm/include/llvm/Support/Parallel.h
+++ llvm/include/llvm/Support/Parallel.h
@@ -48,8 +48,13 @@
   }
 
   void dec() {
-    std::lock_guard<std::mutex> lock(Mutex);
-    if (--Count == 0)
+    bool Zero = false;
+    {
+      std::lock_guard<std::mutex> lock(Mutex);
+      if (--Count == 0)
+        Zero = true;
+    }
+    if (Zero)
       Cond.notify_all();
   }
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D109914.373042.patch
Type: text/x-patch
Size: 1092 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20210916/67050908/attachment.bin>


More information about the llvm-commits mailing list