xref: /llvm-project/llvm/unittests/Support/ThreadPool.cpp (revision 71a7c55f0f021b04b9a7303d0cd391b9161cf303)
1 //========- unittests/Support/ThreadPools.cpp - ThreadPools.h tests --========//
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 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Support/ThreadPool.h"
10 
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SetVector.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Support/CommandLine.h"
16 #include "llvm/Support/Host.h"
17 #include "llvm/Support/Program.h"
18 #include "llvm/Support/TargetSelect.h"
19 #include "llvm/Support/Threading.h"
20 
21 #include "gtest/gtest.h"
22 
23 using namespace llvm;
24 
25 // Fixture for the unittests, allowing to *temporarily* disable the unittests
26 // on a particular platform
27 class ThreadPoolTest : public testing::Test {
28   Triple Host;
29   SmallVector<Triple::ArchType, 4> UnsupportedArchs;
30   SmallVector<Triple::OSType, 4> UnsupportedOSs;
31   SmallVector<Triple::EnvironmentType, 1> UnsupportedEnvironments;
32 protected:
33   // This is intended for platform as a temporary "XFAIL"
34   bool isUnsupportedOSOrEnvironment() {
35     Triple Host(Triple::normalize(sys::getProcessTriple()));
36 
37     if (find(UnsupportedEnvironments, Host.getEnvironment()) !=
38         UnsupportedEnvironments.end())
39       return true;
40 
41     if (is_contained(UnsupportedOSs, Host.getOS()))
42       return true;
43 
44     if (is_contained(UnsupportedArchs, Host.getArch()))
45       return true;
46 
47     return false;
48   }
49 
50   ThreadPoolTest() {
51     // Add unsupported configuration here, example:
52     //   UnsupportedArchs.push_back(Triple::x86_64);
53 
54     // See https://llvm.org/bugs/show_bug.cgi?id=25829
55     UnsupportedArchs.push_back(Triple::ppc64le);
56     UnsupportedArchs.push_back(Triple::ppc64);
57   }
58 
59   /// Make sure this thread not progress faster than the main thread.
60   void waitForMainThread() {
61     std::unique_lock<std::mutex> LockGuard(WaitMainThreadMutex);
62     WaitMainThread.wait(LockGuard, [&] { return MainThreadReady; });
63   }
64 
65   /// Set the readiness of the main thread.
66   void setMainThreadReady() {
67     {
68       std::unique_lock<std::mutex> LockGuard(WaitMainThreadMutex);
69       MainThreadReady = true;
70     }
71     WaitMainThread.notify_all();
72   }
73 
74   void SetUp() override { MainThreadReady = false; }
75 
76   std::vector<llvm::BitVector> RunOnAllSockets(ThreadPoolStrategy S);
77 
78   std::condition_variable WaitMainThread;
79   std::mutex WaitMainThreadMutex;
80   bool MainThreadReady = false;
81 };
82 
83 #define CHECK_UNSUPPORTED()                                                    \
84   do {                                                                         \
85     if (isUnsupportedOSOrEnvironment())                                        \
86       return;                                                                  \
87   } while (0);
88 
89 TEST_F(ThreadPoolTest, AsyncBarrier) {
90   CHECK_UNSUPPORTED();
91   // test that async & barrier work together properly.
92 
93   std::atomic_int checked_in{0};
94 
95   ThreadPool Pool;
96   for (size_t i = 0; i < 5; ++i) {
97     Pool.async([this, &checked_in] {
98       waitForMainThread();
99       ++checked_in;
100     });
101   }
102   ASSERT_EQ(0, checked_in);
103   setMainThreadReady();
104   Pool.wait();
105   ASSERT_EQ(5, checked_in);
106 }
107 
108 static void TestFunc(std::atomic_int &checked_in, int i) { checked_in += i; }
109 
110 TEST_F(ThreadPoolTest, AsyncBarrierArgs) {
111   CHECK_UNSUPPORTED();
112   // Test that async works with a function requiring multiple parameters.
113   std::atomic_int checked_in{0};
114 
115   ThreadPool Pool;
116   for (size_t i = 0; i < 5; ++i) {
117     Pool.async(TestFunc, std::ref(checked_in), i);
118   }
119   Pool.wait();
120   ASSERT_EQ(10, checked_in);
121 }
122 
123 TEST_F(ThreadPoolTest, Async) {
124   CHECK_UNSUPPORTED();
125   ThreadPool Pool;
126   std::atomic_int i{0};
127   Pool.async([this, &i] {
128     waitForMainThread();
129     ++i;
130   });
131   Pool.async([&i] { ++i; });
132   ASSERT_NE(2, i.load());
133   setMainThreadReady();
134   Pool.wait();
135   ASSERT_EQ(2, i.load());
136 }
137 
138 TEST_F(ThreadPoolTest, GetFuture) {
139   CHECK_UNSUPPORTED();
140   ThreadPool Pool(hardware_concurrency(2));
141   std::atomic_int i{0};
142   Pool.async([this, &i] {
143     waitForMainThread();
144     ++i;
145   });
146   // Force the future using get()
147   Pool.async([&i] { ++i; }).get();
148   ASSERT_NE(2, i.load());
149   setMainThreadReady();
150   Pool.wait();
151   ASSERT_EQ(2, i.load());
152 }
153 
154 TEST_F(ThreadPoolTest, PoolDestruction) {
155   CHECK_UNSUPPORTED();
156   // Test that we are waiting on destruction
157   std::atomic_int checked_in{0};
158   {
159     ThreadPool Pool;
160     for (size_t i = 0; i < 5; ++i) {
161       Pool.async([this, &checked_in] {
162         waitForMainThread();
163         ++checked_in;
164       });
165     }
166     ASSERT_EQ(0, checked_in);
167     setMainThreadReady();
168   }
169   ASSERT_EQ(5, checked_in);
170 }
171 
172 #if LLVM_ENABLE_THREADS == 1
173 
174 // FIXME: Skip some tests below on non-Windows because multi-socket systems
175 // were not fully tested on Unix yet, and llvm::get_thread_affinity_mask()
176 // isn't implemented for Unix (need AffinityMask in Support/Unix/Program.inc).
177 #ifdef _WIN32
178 
179 std::vector<llvm::BitVector>
180 ThreadPoolTest::RunOnAllSockets(ThreadPoolStrategy S) {
181   llvm::SetVector<llvm::BitVector> ThreadsUsed;
182   std::mutex Lock;
183   {
184     std::condition_variable AllThreads;
185     std::mutex AllThreadsLock;
186     unsigned Active = 0;
187 
188     ThreadPool Pool(S);
189     for (size_t I = 0; I < S.compute_thread_count(); ++I) {
190       Pool.async([&] {
191         {
192           std::lock_guard<std::mutex> Guard(AllThreadsLock);
193           ++Active;
194           AllThreads.notify_one();
195         }
196         waitForMainThread();
197         std::lock_guard<std::mutex> Guard(Lock);
198         auto Mask = llvm::get_thread_affinity_mask();
199         ThreadsUsed.insert(Mask);
200       });
201     }
202     EXPECT_EQ(true, ThreadsUsed.empty());
203     {
204       std::unique_lock<std::mutex> Guard(AllThreadsLock);
205       AllThreads.wait(Guard,
206                       [&]() { return Active == S.compute_thread_count(); });
207     }
208     setMainThreadReady();
209   }
210   return ThreadsUsed.takeVector();
211 }
212 
213 TEST_F(ThreadPoolTest, AllThreads_UseAllRessources) {
214   CHECK_UNSUPPORTED();
215   std::vector<llvm::BitVector> ThreadsUsed = RunOnAllSockets({});
216   ASSERT_EQ(llvm::get_cpus(), ThreadsUsed.size());
217 }
218 
219 TEST_F(ThreadPoolTest, AllThreads_OneThreadPerCore) {
220   CHECK_UNSUPPORTED();
221   std::vector<llvm::BitVector> ThreadsUsed =
222       RunOnAllSockets(llvm::heavyweight_hardware_concurrency());
223   ASSERT_EQ(llvm::get_cpus(), ThreadsUsed.size());
224 }
225 
226 // From TestMain.cpp.
227 extern const char *TestMainArgv0;
228 
229 // Just a reachable symbol to ease resolving of the executable's path.
230 static cl::opt<std::string> ThreadPoolTestStringArg1("thread-pool-string-arg1");
231 
232 #ifdef _WIN32
233 #define setenv(name, var, ignore) _putenv_s(name, var)
234 #endif
235 
236 TEST_F(ThreadPoolTest, AffinityMask) {
237   CHECK_UNSUPPORTED();
238 
239   // Skip this test if less than 4 threads are available.
240   if (llvm::hardware_concurrency().compute_thread_count() < 4)
241     return;
242 
243   using namespace llvm::sys;
244   if (getenv("LLVM_THREADPOOL_AFFINITYMASK")) {
245     std::vector<llvm::BitVector> ThreadsUsed = RunOnAllSockets({});
246     // Ensure the threads only ran on CPUs 0-3.
247     // NOTE: Don't use ASSERT* here because this runs in a subprocess,
248     // and will show up as un-executed in the parent.
249     assert(llvm::all_of(ThreadsUsed,
250                         [](auto &T) { return T.getData().front() < 16UL; }) &&
251            "Threads ran on more CPUs than expected! The affinity mask does not "
252            "seem to work.");
253     return;
254   }
255   std::string Executable =
256       sys::fs::getMainExecutable(TestMainArgv0, &ThreadPoolTestStringArg1);
257   StringRef argv[] = {Executable, "--gtest_filter=ThreadPoolTest.AffinityMask"};
258 
259   // Add environment variable to the environment of the child process.
260   int Res = setenv("LLVM_THREADPOOL_AFFINITYMASK", "1", false);
261   ASSERT_EQ(Res, 0);
262 
263   std::string Error;
264   bool ExecutionFailed;
265   BitVector Affinity;
266   Affinity.resize(4);
267   Affinity.set(0, 4); // Use CPUs 0,1,2,3.
268   int Ret = sys::ExecuteAndWait(Executable, argv, {}, {}, 0, 0, &Error,
269                                 &ExecutionFailed, nullptr, &Affinity);
270   ASSERT_EQ(0, Ret);
271 }
272 
273 #endif // #ifdef _WIN32
274 #endif // #if LLVM_ENABLE_THREADS == 1
275