| 1 |
/*========================== begin_copyright_notice ============================ |
| 2 |
|
| 3 |
Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
See https://llvm.org/LICENSE.txt for license information. |
| 5 |
SPDX-License-Identifier: Apache-2.0 with LLVM-exception |
| 6 |
|
| 7 |
============================= end_copyright_notice ===========================*/ |
| 8 |
|
| 9 |
From 7b25fa8c7a151e94be46ed8f0a56bf4e2af1c104 Mon Sep 17 00:00:00 2001 |
| 10 |
From: Alexandre Ganea <[email protected]> |
| 11 |
Date: Sat, 18 Sep 2021 12:00:17 -0400 |
| 12 |
Subject: [PATCH] [Support] Attempt to fix deadlock in ThreadGroup |
| 13 |
|
| 14 |
This is an attempt to fix the situation described by https://reviews.llvm.org/D104207#2826290 and PR41508. |
| 15 |
See sequence of operations leading to the bug in https://reviews.llvm.org/D104207#3004689 |
| 16 |
|
| 17 |
We ensure that the Latch is completely "free" before decrementing the number of TaskGroupInstances. |
| 18 |
|
| 19 |
Differential revision: https://reviews.llvm.org/D109914 |
| 20 |
--- |
| 21 |
llvm/include/llvm/Support/Parallel.h | 5 ++++- |
| 22 |
llvm/lib/Support/Parallel.cpp | 7 ++++++- |
| 23 |
2 files changed, 10 insertions(+), 2 deletions(-) |
| 24 |
|
| 25 |
diff --git a/llvm/include/llvm/Support/Parallel.h b/llvm/include/llvm/Support/Parallel.h |
| 26 |
index 28d171d452560..5c3b26d5754c2 100644 |
| 27 |
--- a/llvm/include/llvm/Support/Parallel.h |
| 28 |
+++ b/llvm/include/llvm/Support/Parallel.h |
| 29 |
@@ -40,7 +40,10 @@ class Latch { |
| 30 |
|
| 31 |
public: |
| 32 |
explicit Latch(uint32_t Count = 0) : Count(Count) {} |
| 33 |
- ~Latch() { sync(); } |
| 34 |
+ ~Latch() { |
| 35 |
+ // Ensure at least that sync() was called. |
| 36 |
+ assert(Count == 0); |
| 37 |
+ } |
| 38 |
|
| 39 |
void inc() { |
| 40 |
std::lock_guard<std::mutex> lock(Mutex); |
| 41 |
diff --git a/llvm/lib/Support/Parallel.cpp b/llvm/lib/Support/Parallel.cpp |
| 42 |
index 9a2e1003da5a2..71e3a1362f7eb 100644 |
| 43 |
--- a/llvm/lib/Support/Parallel.cpp |
| 44 |
+++ b/llvm/lib/Support/Parallel.cpp |
| 45 |
@@ -151,7 +151,12 @@ static std::atomic<int> TaskGroupInstances; |
| 46 |
// lock, only allow the first TaskGroup to run tasks parallelly. In the scenario |
| 47 |
// of nested parallel_for_each(), only the outermost one runs parallelly. |
| 48 |
TaskGroup::TaskGroup() : Parallel(TaskGroupInstances++ == 0) {} |
| 49 |
-TaskGroup::~TaskGroup() { --TaskGroupInstances; } |
| 50 |
+TaskGroup::~TaskGroup() { |
| 51 |
+ // We must ensure that all the workloads have finished before decrementing the |
| 52 |
+ // instances count. |
| 53 |
+ L.sync(); |
| 54 |
+ --TaskGroupInstances; |
| 55 |
+} |
| 56 |
|
| 57 |
void TaskGroup::spawn(std::function<void()> F) { |
| 58 |
if (Parallel) { |
| 59 |
|