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/Config/llvm-config.h" // for LLVM_ENABLE_THREADS
11 #include "llvm/Support/thread.h"
12 #include "llvm/TargetParser/Host.h"
13 #include "llvm/TargetParser/Triple.h"
14 #include "gtest/gtest.h"
17 #include <condition_variable>
23 static bool isThreadingSupportedArchAndOS() {
24 #if LLVM_ENABLE_THREADS
25 Triple
Host(Triple::normalize(sys::getProcessTriple()));
27 // Initially this is only testing detection of the number of
28 // physical cores, which is currently only supported/tested on
30 return (Host
.isOSWindows() && llvm_is_multithreaded()) || Host
.isOSDarwin() ||
31 (Host
.isX86() && Host
.isOSLinux()) ||
32 (Host
.isOSLinux() && !Host
.isAndroid()) ||
33 (Host
.isSystemZ() && Host
.isOSzOS()) || Host
.isOSAIX();
39 TEST(Threading
, PhysicalConcurrency
) {
40 auto Num
= heavyweight_hardware_concurrency();
41 // Since Num is unsigned this will also catch us trying to
43 ASSERT_LE(Num
.compute_thread_count(),
44 hardware_concurrency().compute_thread_count());
47 TEST(Threading
, NumPhysicalCoresSupported
) {
48 if (!isThreadingSupportedArchAndOS())
50 int Num
= get_physical_cores();
54 TEST(Threading
, NumPhysicalCoresUnsupported
) {
55 if (isThreadingSupportedArchAndOS())
57 int Num
= get_physical_cores();
61 #if LLVM_ENABLE_THREADS
67 std::lock_guard
<std::mutex
> Lock(M
);
69 // Broadcast with the lock held, so it's safe to destroy the Notification
70 // after wait() returns.
76 std::unique_lock
<std::mutex
> Lock(M
);
77 using steady_clock
= std::chrono::steady_clock
;
78 auto Deadline
= steady_clock::now() +
79 std::chrono::duration_cast
<steady_clock::duration
>(
80 std::chrono::duration
<double>(5));
81 return CV
.wait_until(Lock
, Deadline
, [this] { return Notified
; });
85 bool Notified
= false;
86 mutable std::condition_variable CV
;
90 TEST(Threading
, RunOnThreadSyncAsync
) {
91 Notification ThreadStarted
, ThreadAdvanced
, ThreadFinished
;
93 auto ThreadFunc
= [&] {
94 ThreadStarted
.notify();
95 ASSERT_TRUE(ThreadAdvanced
.wait());
96 ThreadFinished
.notify();
99 llvm::thread
Thread(ThreadFunc
);
101 ASSERT_TRUE(ThreadStarted
.wait());
102 ThreadAdvanced
.notify();
103 ASSERT_TRUE(ThreadFinished
.wait());
106 TEST(Threading
, RunOnThreadSync
) {
107 std::atomic_bool
Executed(false);
109 [](void *Arg
) { *static_cast<std::atomic_bool
*>(Arg
) = true; },
112 ASSERT_EQ(Executed
, true);
115 #if defined(__APPLE__)
116 TEST(Threading
, AppleStackSize
) {
117 llvm::thread
Thread([] {
118 volatile unsigned char Var
[8 * 1024 * 1024 - 10240];
120 ASSERT_EQ(Var
[0], 0xff);