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"
21 #include "gtest/gtest.h"
25 // Fixture for the unittests, allowing to *temporarily* disable the unittests
26 // on a particular platform
27 class ThreadPoolTest
: public testing::Test
{
29 SmallVector
<Triple::ArchType
, 4> UnsupportedArchs
;
30 SmallVector
<Triple::OSType
, 4> UnsupportedOSs
;
31 SmallVector
<Triple::EnvironmentType
, 1> UnsupportedEnvironments
;
33 // This is intended for platform as a temporary "XFAIL"
34 bool isUnsupportedOSOrEnvironment() {
35 Triple
Host(Triple::normalize(sys::getProcessTriple()));
37 if (find(UnsupportedEnvironments
, Host
.getEnvironment()) !=
38 UnsupportedEnvironments
.end())
41 if (is_contained(UnsupportedOSs
, Host
.getOS()))
44 if (is_contained(UnsupportedArchs
, Host
.getArch()))
51 // Add unsupported configuration here, example:
52 // UnsupportedArchs.push_back(Triple::x86_64);
54 // See https://llvm.org/bugs/show_bug.cgi?id=25829
55 UnsupportedArchs
.push_back(Triple::ppc64le
);
56 UnsupportedArchs
.push_back(Triple::ppc64
);
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
; });
65 /// Set the readiness of the main thread.
66 void setMainThreadReady() {
68 std::unique_lock
<std::mutex
> LockGuard(WaitMainThreadMutex
);
69 MainThreadReady
= true;
71 WaitMainThread
.notify_all();
74 void SetUp() override
{ MainThreadReady
= false; }
76 std::vector
<llvm::BitVector
> RunOnAllSockets(ThreadPoolStrategy S
);
78 std::condition_variable WaitMainThread
;
79 std::mutex WaitMainThreadMutex
;
80 bool MainThreadReady
= false;
83 #define CHECK_UNSUPPORTED() \
85 if (isUnsupportedOSOrEnvironment()) \
89 TEST_F(ThreadPoolTest
, AsyncBarrier
) {
91 // test that async & barrier work together properly.
93 std::atomic_int checked_in
{0};
96 for (size_t i
= 0; i
< 5; ++i
) {
97 Pool
.async([this, &checked_in
] {
102 ASSERT_EQ(0, checked_in
);
103 setMainThreadReady();
105 ASSERT_EQ(5, checked_in
);
108 static void TestFunc(std::atomic_int
&checked_in
, int i
) { checked_in
+= i
; }
110 TEST_F(ThreadPoolTest
, AsyncBarrierArgs
) {
112 // Test that async works with a function requiring multiple parameters.
113 std::atomic_int checked_in
{0};
116 for (size_t i
= 0; i
< 5; ++i
) {
117 Pool
.async(TestFunc
, std::ref(checked_in
), i
);
120 ASSERT_EQ(10, checked_in
);
123 TEST_F(ThreadPoolTest
, Async
) {
126 std::atomic_int i
{0};
127 Pool
.async([this, &i
] {
131 Pool
.async([&i
] { ++i
; });
132 ASSERT_NE(2, i
.load());
133 setMainThreadReady();
135 ASSERT_EQ(2, i
.load());
138 TEST_F(ThreadPoolTest
, GetFuture
) {
140 ThreadPool
Pool(hardware_concurrency(2));
141 std::atomic_int i
{0};
142 Pool
.async([this, &i
] {
146 // Force the future using get()
147 Pool
.async([&i
] { ++i
; }).get();
148 ASSERT_NE(2, i
.load());
149 setMainThreadReady();
151 ASSERT_EQ(2, i
.load());
154 TEST_F(ThreadPoolTest
, GetFutureWithResult
) {
156 ThreadPool
Pool(hardware_concurrency(2));
157 auto F1
= Pool
.async([] { return 1; });
158 auto F2
= Pool
.async([] { return 2; });
160 setMainThreadReady();
162 ASSERT_EQ(1, F1
.get());
163 ASSERT_EQ(2, F2
.get());
166 TEST_F(ThreadPoolTest
, GetFutureWithResultAndArgs
) {
168 ThreadPool
Pool(hardware_concurrency(2));
169 auto Fn
= [](int x
) { return x
; };
170 auto F1
= Pool
.async(Fn
, 1);
171 auto F2
= Pool
.async(Fn
, 2);
173 setMainThreadReady();
175 ASSERT_EQ(1, F1
.get());
176 ASSERT_EQ(2, F2
.get());
179 TEST_F(ThreadPoolTest
, PoolDestruction
) {
181 // Test that we are waiting on destruction
182 std::atomic_int checked_in
{0};
185 for (size_t i
= 0; i
< 5; ++i
) {
186 Pool
.async([this, &checked_in
] {
191 ASSERT_EQ(0, checked_in
);
192 setMainThreadReady();
194 ASSERT_EQ(5, checked_in
);
197 #if LLVM_ENABLE_THREADS == 1
199 // FIXME: Skip some tests below on non-Windows because multi-socket systems
200 // were not fully tested on Unix yet, and llvm::get_thread_affinity_mask()
201 // isn't implemented for Unix (need AffinityMask in Support/Unix/Program.inc).
204 std::vector
<llvm::BitVector
>
205 ThreadPoolTest::RunOnAllSockets(ThreadPoolStrategy S
) {
206 llvm::SetVector
<llvm::BitVector
> ThreadsUsed
;
209 std::condition_variable AllThreads
;
210 std::mutex AllThreadsLock
;
214 for (size_t I
= 0; I
< S
.compute_thread_count(); ++I
) {
217 std::lock_guard
<std::mutex
> Guard(AllThreadsLock
);
219 AllThreads
.notify_one();
222 std::lock_guard
<std::mutex
> Guard(Lock
);
223 auto Mask
= llvm::get_thread_affinity_mask();
224 ThreadsUsed
.insert(Mask
);
227 EXPECT_EQ(true, ThreadsUsed
.empty());
229 std::unique_lock
<std::mutex
> Guard(AllThreadsLock
);
230 AllThreads
.wait(Guard
,
231 [&]() { return Active
== S
.compute_thread_count(); });
233 setMainThreadReady();
235 return ThreadsUsed
.takeVector();
238 TEST_F(ThreadPoolTest
, AllThreads_UseAllRessources
) {
240 std::vector
<llvm::BitVector
> ThreadsUsed
= RunOnAllSockets({});
241 ASSERT_EQ(llvm::get_cpus(), ThreadsUsed
.size());
244 TEST_F(ThreadPoolTest
, AllThreads_OneThreadPerCore
) {
246 std::vector
<llvm::BitVector
> ThreadsUsed
=
247 RunOnAllSockets(llvm::heavyweight_hardware_concurrency());
248 ASSERT_EQ(llvm::get_cpus(), ThreadsUsed
.size());
251 // From TestMain.cpp.
252 extern const char *TestMainArgv0
;
254 // Just a reachable symbol to ease resolving of the executable's path.
255 static cl::opt
<std::string
> ThreadPoolTestStringArg1("thread-pool-string-arg1");
258 #define setenv(name, var, ignore) _putenv_s(name, var)
261 TEST_F(ThreadPoolTest
, AffinityMask
) {
264 // Skip this test if less than 4 threads are available.
265 if (llvm::hardware_concurrency().compute_thread_count() < 4)
268 using namespace llvm::sys
;
269 if (getenv("LLVM_THREADPOOL_AFFINITYMASK")) {
270 std::vector
<llvm::BitVector
> ThreadsUsed
= RunOnAllSockets({});
271 // Ensure the threads only ran on CPUs 0-3.
272 // NOTE: Don't use ASSERT* here because this runs in a subprocess,
273 // and will show up as un-executed in the parent.
274 assert(llvm::all_of(ThreadsUsed
,
275 [](auto &T
) { return T
.getData().front() < 16UL; }) &&
276 "Threads ran on more CPUs than expected! The affinity mask does not "
280 std::string Executable
=
281 sys::fs::getMainExecutable(TestMainArgv0
, &ThreadPoolTestStringArg1
);
282 StringRef argv
[] = {Executable
, "--gtest_filter=ThreadPoolTest.AffinityMask"};
284 // Add environment variable to the environment of the child process.
285 int Res
= setenv("LLVM_THREADPOOL_AFFINITYMASK", "1", false);
289 bool ExecutionFailed
;
292 Affinity
.set(0, 4); // Use CPUs 0,1,2,3.
293 int Ret
= sys::ExecuteAndWait(Executable
, argv
, {}, {}, 0, 0, &Error
,
294 &ExecutionFailed
, nullptr, &Affinity
);
298 #endif // #ifdef _WIN32
299 #endif // #if LLVM_ENABLE_THREADS == 1