[Support] Avoid using main thread for llvm::parallelFor().
authorAlexey Lapshin <a.v.lapshin@mail.ru>
Tue, 24 Jan 2023 13:05:43 +0000 (14:05 +0100)
committerAlexey Lapshin <a.v.lapshin@mail.ru>
Wed, 25 Jan 2023 11:46:04 +0000 (12:46 +0100)
The llvm::parallelFor() uses threads created by ThreadPoolExecutor as well as main thread.
The index for the main thread matches with the index for the first thread created by ThreadPoolExecutor.
It results in that getThreadIndex returns the same value for different threads.
To avoid thread index clashing - do not use main thread for llvm::parallelFor():

parallel::TaskGroup TG;
for (; Begin + TaskSize < End; Begin += TaskSize) {
  TG.spawn([=, &Fn] {
    for (size_t I = Begin, E = Begin + TaskSize; I != E; ++I)
      Fn(I);
  });
}
for (; Begin != End; ++Begin)    <<<< executed by main thread.
  Fn(Begin);                     <<<<
return;                          <<<<

Differential Revision: https://reviews.llvm.org/D142317

llvm/lib/Support/Parallel.cpp

index 23ed9d8..c256d25 100644 (file)
@@ -214,8 +214,12 @@ void llvm::parallelFor(size_t Begin, size_t End,
           Fn(I);
       });
     }
-    for (; Begin != End; ++Begin)
-      Fn(Begin);
+    if (Begin != End) {
+      TG.spawn([=, &Fn] {
+        for (size_t I = Begin; I != End; ++I)
+          Fn(I);
+      });
+    }
     return;
   }
 #endif