1 //===- unittests/Threading.cpp - Thread 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/Threading.h"
10 #include "llvm/Support/thread.h"
11 #include "llvm/TargetParser/Host.h"
12 #include "llvm/TargetParser/Triple.h"
13 #include "gtest/gtest.h"
16 #include <condition_variable>
22 static bool isThreadingSupportedArchAndOS() {
23 #if LLVM_ENABLE_THREADS
24 Triple
Host(Triple::normalize(sys::getProcessTriple()));
26 // Initially this is only testing detection of the number of
27 // physical cores, which is currently only supported/tested on
29 return (Host
.isOSWindows() && llvm_is_multithreaded()) || Host
.isOSDarwin() ||
30 (Host
.isX86() && Host
.isOSLinux()) ||
31 (Host
.isOSLinux() && !Host
.isAndroid()) ||
32 (Host
.isSystemZ() && Host
.isOSzOS()) || Host
.isOSAIX();
38 TEST(Threading
, PhysicalConcurrency
) {
39 auto Num
= heavyweight_hardware_concurrency();
40 // Since Num is unsigned this will also catch us trying to
42 ASSERT_LE(Num
.compute_thread_count(),
43 hardware_concurrency().compute_thread_count());
46 TEST(Threading
, NumPhysicalCoresSupported
) {
47 if (!isThreadingSupportedArchAndOS())
49 int Num
= get_physical_cores();
53 TEST(Threading
, NumPhysicalCoresUnsupported
) {
54 if (isThreadingSupportedArchAndOS())
56 int Num
= get_physical_cores();
60 #if LLVM_ENABLE_THREADS
66 std::lock_guard
<std::mutex
> Lock(M
);
68 // Broadcast with the lock held, so it's safe to destroy the Notification
69 // after wait() returns.
75 std::unique_lock
<std::mutex
> Lock(M
);
76 using steady_clock
= std::chrono::steady_clock
;
77 auto Deadline
= steady_clock::now() +
78 std::chrono::duration_cast
<steady_clock::duration
>(
79 std::chrono::duration
<double>(5));
80 return CV
.wait_until(Lock
, Deadline
, [this] { return Notified
; });
84 bool Notified
= false;
85 mutable std::condition_variable CV
;
89 TEST(Threading
, RunOnThreadSyncAsync
) {
90 Notification ThreadStarted
, ThreadAdvanced
, ThreadFinished
;
92 auto ThreadFunc
= [&] {
93 ThreadStarted
.notify();
94 ASSERT_TRUE(ThreadAdvanced
.wait());
95 ThreadFinished
.notify();
98 llvm::thread
Thread(ThreadFunc
);
100 ASSERT_TRUE(ThreadStarted
.wait());
101 ThreadAdvanced
.notify();
102 ASSERT_TRUE(ThreadFinished
.wait());
105 TEST(Threading
, RunOnThreadSync
) {
106 std::atomic_bool
Executed(false);
108 [](void *Arg
) { *static_cast<std::atomic_bool
*>(Arg
) = true; },
111 ASSERT_EQ(Executed
, true);
114 #if defined(__APPLE__)
115 TEST(Threading
, AppleStackSize
) {
116 llvm::thread
Thread([] {
117 volatile unsigned char Var
[8 * 1024 * 1024 - 10240];
119 ASSERT_EQ(Var
[0], 0xff);