1 //========- unittests/Support/ThreadPools.cpp - ThreadPools.h tests --========//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Support/ThreadPool.h"
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"
24 #include "gtest/gtest.h"
28 // Fixture for the unittests, allowing to *temporarily* disable the unittests
29 // on a particular platform
30 class ThreadPoolTest
: public testing::Test
{
32 SmallVector
<Triple::ArchType
, 4> UnsupportedArchs
;
33 SmallVector
<Triple::OSType
, 4> UnsupportedOSs
;
34 SmallVector
<Triple::EnvironmentType
, 1> UnsupportedEnvironments
;
37 // This is intended for platform as a temporary "XFAIL"
38 bool isUnsupportedOSOrEnvironment() {
39 Triple
Host(Triple::normalize(sys::getProcessTriple()));
41 if (find(UnsupportedEnvironments
, Host
.getEnvironment()) !=
42 UnsupportedEnvironments
.end())
45 if (is_contained(UnsupportedOSs
, Host
.getOS()))
48 if (is_contained(UnsupportedArchs
, Host
.getArch()))
55 // Add unsupported configuration here, example:
56 // UnsupportedArchs.push_back(Triple::x86_64);
58 // See https://llvm.org/bugs/show_bug.cgi?id=25829
59 UnsupportedArchs
.push_back(Triple::ppc64le
);
60 UnsupportedArchs
.push_back(Triple::ppc64
);
63 /// Make sure this thread not progress faster than the main thread.
64 void waitForMainThread() { waitForPhase(1); }
66 /// Set the readiness of the main thread.
67 void setMainThreadReady() { setPhase(1); }
69 /// Wait until given phase is set using setPhase(); first "main" phase is 1.
70 /// See also PhaseResetHelper below.
71 void waitForPhase(int Phase
) {
72 std::unique_lock
<std::mutex
> LockGuard(CurrentPhaseMutex
);
73 CurrentPhaseCondition
.wait(
74 LockGuard
, [&] { return CurrentPhase
== Phase
|| CurrentPhase
< 0; });
76 /// If a thread waits on another phase, the test could bail out on a failed
77 /// assertion and ThreadPool destructor would wait() on all threads, which
78 /// would deadlock on the task waiting. Create this helper to automatically
79 /// reset the phase and unblock such threads.
80 struct PhaseResetHelper
{
81 PhaseResetHelper(ThreadPoolTest
*test
) : test(test
) {}
82 ~PhaseResetHelper() { test
->setPhase(-1); }
86 /// Advance to the given phase.
87 void setPhase(int Phase
) {
89 std::unique_lock
<std::mutex
> LockGuard(CurrentPhaseMutex
);
90 assert(Phase
== CurrentPhase
+ 1 || Phase
< 0);
93 CurrentPhaseCondition
.notify_all();
96 void SetUp() override
{ CurrentPhase
= 0; }
98 std::vector
<llvm::BitVector
> RunOnAllSockets(ThreadPoolStrategy S
);
100 std::condition_variable CurrentPhaseCondition
;
101 std::mutex CurrentPhaseMutex
;
102 int CurrentPhase
; // -1 = error, 0 = setup, 1 = ready, 2+ = custom
105 #define CHECK_UNSUPPORTED() \
107 if (isUnsupportedOSOrEnvironment()) \
111 TEST_F(ThreadPoolTest
, AsyncBarrier
) {
113 // test that async & barrier work together properly.
115 std::atomic_int checked_in
{0};
118 for (size_t i
= 0; i
< 5; ++i
) {
119 Pool
.async([this, &checked_in
] {
124 ASSERT_EQ(0, checked_in
);
125 setMainThreadReady();
127 ASSERT_EQ(5, checked_in
);
130 static void TestFunc(std::atomic_int
&checked_in
, int i
) { checked_in
+= i
; }
132 TEST_F(ThreadPoolTest
, AsyncBarrierArgs
) {
134 // Test that async works with a function requiring multiple parameters.
135 std::atomic_int checked_in
{0};
138 for (size_t i
= 0; i
< 5; ++i
) {
139 Pool
.async(TestFunc
, std::ref(checked_in
), i
);
142 ASSERT_EQ(10, checked_in
);
145 TEST_F(ThreadPoolTest
, Async
) {
148 std::atomic_int i
{0};
149 Pool
.async([this, &i
] {
153 Pool
.async([&i
] { ++i
; });
154 ASSERT_NE(2, i
.load());
155 setMainThreadReady();
157 ASSERT_EQ(2, i
.load());
160 TEST_F(ThreadPoolTest
, GetFuture
) {
162 ThreadPool
Pool(hardware_concurrency(2));
163 std::atomic_int i
{0};
164 Pool
.async([this, &i
] {
168 // Force the future using get()
169 Pool
.async([&i
] { ++i
; }).get();
170 ASSERT_NE(2, i
.load());
171 setMainThreadReady();
173 ASSERT_EQ(2, i
.load());
176 TEST_F(ThreadPoolTest
, GetFutureWithResult
) {
178 ThreadPool
Pool(hardware_concurrency(2));
179 auto F1
= Pool
.async([] { return 1; });
180 auto F2
= Pool
.async([] { return 2; });
182 setMainThreadReady();
184 ASSERT_EQ(1, F1
.get());
185 ASSERT_EQ(2, F2
.get());
188 TEST_F(ThreadPoolTest
, GetFutureWithResultAndArgs
) {
190 ThreadPool
Pool(hardware_concurrency(2));
191 auto Fn
= [](int x
) { return x
; };
192 auto F1
= Pool
.async(Fn
, 1);
193 auto F2
= Pool
.async(Fn
, 2);
195 setMainThreadReady();
197 ASSERT_EQ(1, F1
.get());
198 ASSERT_EQ(2, F2
.get());
201 TEST_F(ThreadPoolTest
, PoolDestruction
) {
203 // Test that we are waiting on destruction
204 std::atomic_int checked_in
{0};
207 for (size_t i
= 0; i
< 5; ++i
) {
208 Pool
.async([this, &checked_in
] {
213 ASSERT_EQ(0, checked_in
);
214 setMainThreadReady();
216 ASSERT_EQ(5, checked_in
);
219 // Check running tasks in different groups.
220 TEST_F(ThreadPoolTest
, Groups
) {
222 // Need at least two threads, as the task in group2
223 // might block a thread until all tasks in group1 finish.
224 ThreadPoolStrategy S
= hardware_concurrency(2);
225 if (S
.compute_thread_count() < 2)
228 PhaseResetHelper
Helper(this);
229 ThreadPoolTaskGroup
Group1(Pool
);
230 ThreadPoolTaskGroup
Group2(Pool
);
232 // Check that waiting for an empty group is a no-op.
235 std::atomic_int checked_in1
{0};
236 std::atomic_int checked_in2
{0};
238 for (size_t i
= 0; i
< 5; ++i
) {
239 Group1
.async([this, &checked_in1
] {
244 Group2
.async([this, &checked_in2
] {
248 ASSERT_EQ(0, checked_in1
);
249 ASSERT_EQ(0, checked_in2
);
250 // Start first group and wait for it.
251 setMainThreadReady();
253 ASSERT_EQ(5, checked_in1
);
254 // Second group has not yet finished, start it and wait for it.
255 ASSERT_EQ(0, checked_in2
);
258 ASSERT_EQ(5, checked_in1
);
259 ASSERT_EQ(1, checked_in2
);
262 // Check recursive tasks.
263 TEST_F(ThreadPoolTest
, RecursiveGroups
) {
266 ThreadPoolTaskGroup
Group(Pool
);
268 std::atomic_int checked_in1
{0};
270 for (size_t i
= 0; i
< 5; ++i
) {
271 Group
.async([this, &Pool
, &checked_in1
] {
274 ThreadPoolTaskGroup
LocalGroup(Pool
);
276 // Check that waiting for an empty group is a no-op.
279 std::atomic_int checked_in2
{0};
280 for (size_t i
= 0; i
< 5; ++i
) {
281 LocalGroup
.async([&checked_in2
] { ++checked_in2
; });
284 ASSERT_EQ(5, checked_in2
);
289 ASSERT_EQ(0, checked_in1
);
290 setMainThreadReady();
292 ASSERT_EQ(5, checked_in1
);
295 TEST_F(ThreadPoolTest
, RecursiveWaitDeadlock
) {
297 ThreadPoolStrategy S
= hardware_concurrency(2);
298 if (S
.compute_thread_count() < 2)
301 PhaseResetHelper
Helper(this);
302 ThreadPoolTaskGroup
Group(Pool
);
304 // Test that a thread calling wait() for a group and is waiting for more tasks
305 // returns when the last task finishes in a different thread while the waiting
306 // thread was waiting for more tasks to process while waiting.
308 // Task A runs in the first thread. It finishes and leaves
309 // the background thread waiting for more tasks.
314 // Task B is run in a second thread, it launches yet another
315 // task C in a different group, which will be handled by the waiting
316 // thread started above.
317 Group
.async([this, &Pool
] {
319 ThreadPoolTaskGroup
LocalGroup(Pool
);
320 LocalGroup
.async([this] {
322 // Give the other thread enough time to check that there's no task
323 // to process and suspend waiting for a notification. This is indeed racy,
324 // but probably the best that can be done.
325 std::this_thread::sleep_for(std::chrono::milliseconds(10));
327 // And task B only now will wait for the tasks in the group (=task C)
328 // to finish. This test checks that it does not deadlock. If the
329 // `NotifyGroup` handling in ThreadPool::processTasks() didn't take place,
330 // this task B would be stuck waiting for tasks to arrive.
334 setMainThreadReady();
338 #if LLVM_ENABLE_THREADS == 1
340 // FIXME: Skip some tests below on non-Windows because multi-socket systems
341 // were not fully tested on Unix yet, and llvm::get_thread_affinity_mask()
342 // isn't implemented for Unix (need AffinityMask in Support/Unix/Program.inc).
345 std::vector
<llvm::BitVector
>
346 ThreadPoolTest::RunOnAllSockets(ThreadPoolStrategy S
) {
347 llvm::SetVector
<llvm::BitVector
> ThreadsUsed
;
350 std::condition_variable AllThreads
;
351 std::mutex AllThreadsLock
;
355 for (size_t I
= 0; I
< S
.compute_thread_count(); ++I
) {
358 std::lock_guard
<std::mutex
> Guard(AllThreadsLock
);
360 AllThreads
.notify_one();
363 std::lock_guard
<std::mutex
> Guard(Lock
);
364 auto Mask
= llvm::get_thread_affinity_mask();
365 ThreadsUsed
.insert(Mask
);
368 EXPECT_EQ(true, ThreadsUsed
.empty());
370 std::unique_lock
<std::mutex
> Guard(AllThreadsLock
);
371 AllThreads
.wait(Guard
,
372 [&]() { return Active
== S
.compute_thread_count(); });
374 setMainThreadReady();
376 return ThreadsUsed
.takeVector();
379 TEST_F(ThreadPoolTest
, AllThreads_UseAllRessources
) {
381 std::vector
<llvm::BitVector
> ThreadsUsed
= RunOnAllSockets({});
382 ASSERT_EQ(llvm::get_cpus(), ThreadsUsed
.size());
385 TEST_F(ThreadPoolTest
, AllThreads_OneThreadPerCore
) {
387 std::vector
<llvm::BitVector
> ThreadsUsed
=
388 RunOnAllSockets(llvm::heavyweight_hardware_concurrency());
389 ASSERT_EQ(llvm::get_cpus(), ThreadsUsed
.size());
392 // From TestMain.cpp.
393 extern const char *TestMainArgv0
;
395 // Just a reachable symbol to ease resolving of the executable's path.
396 static cl::opt
<std::string
> ThreadPoolTestStringArg1("thread-pool-string-arg1");
399 #define setenv(name, var, ignore) _putenv_s(name, var)
402 TEST_F(ThreadPoolTest
, AffinityMask
) {
405 // Skip this test if less than 4 threads are available.
406 if (llvm::hardware_concurrency().compute_thread_count() < 4)
409 using namespace llvm::sys
;
410 if (getenv("LLVM_THREADPOOL_AFFINITYMASK")) {
411 std::vector
<llvm::BitVector
> ThreadsUsed
= RunOnAllSockets({});
412 // Ensure the threads only ran on CPUs 0-3.
413 // NOTE: Don't use ASSERT* here because this runs in a subprocess,
414 // and will show up as un-executed in the parent.
415 assert(llvm::all_of(ThreadsUsed
,
416 [](auto &T
) { return T
.getData().front() < 16UL; }) &&
417 "Threads ran on more CPUs than expected! The affinity mask does not "
421 std::string Executable
=
422 sys::fs::getMainExecutable(TestMainArgv0
, &ThreadPoolTestStringArg1
);
423 StringRef argv
[] = {Executable
, "--gtest_filter=ThreadPoolTest.AffinityMask"};
425 // Add environment variable to the environment of the child process.
426 int Res
= setenv("LLVM_THREADPOOL_AFFINITYMASK", "1", false);
430 bool ExecutionFailed
;
433 Affinity
.set(0, 4); // Use CPUs 0,1,2,3.
434 int Ret
= sys::ExecuteAndWait(Executable
, argv
, {}, {}, 0, 0, &Error
,
435 &ExecutionFailed
, nullptr, &Affinity
);
439 #endif // #ifdef _WIN32
440 #endif // #if LLVM_ENABLE_THREADS == 1