blob: 5457cdc1c683aea6fb55c17a671e45ec0dce3bff [file] [log] [blame]
Mehdi Amini33a7ea42015-12-15 00:59:19 +00001//========- unittests/Support/ThreadPools.cpp - ThreadPools.h tests --========//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Support/ThreadPool.h"
11
12#include "llvm/ADT/STLExtras.h"
13
14#include "gtest/gtest.h"
15
16using namespace llvm;
17using namespace std::chrono;
18
19/// Try best to make this thread not progress faster than the main thread
20static void yield() {
21#ifdef LLVM_ENABLE_THREADS
22 std::this_thread::yield();
23#endif
24 std::this_thread::sleep_for(milliseconds(200));
25#ifdef LLVM_ENABLE_THREADS
26 std::this_thread::yield();
27#endif
28}
29
30TEST(ThreadPoolTest, AsyncBarrier) {
31 // test that async & barrier work together properly.
32
33 std::atomic_int checked_in{0};
34
35 ThreadPool Pool;
36 for (size_t i = 0; i < 5; ++i) {
37 Pool.async([&checked_in, i] {
38 yield();
39 ++checked_in;
40 });
41 }
42 ASSERT_EQ(0, checked_in);
43 Pool.wait();
44 ASSERT_EQ(5, checked_in);
45}
46
Teresa Johnsonf064d622015-12-15 04:44:02 +000047static void TestFunc(std::atomic_int &checked_in, int i) { checked_in += i; }
48
49TEST(ThreadPoolTest, AsyncBarrierArgs) {
50 // Test that async works with a function requiring multiple parameters.
51 std::atomic_int checked_in{0};
52
53 ThreadPool Pool;
54 for (size_t i = 0; i < 5; ++i) {
55 Pool.async(TestFunc, std::ref(checked_in), i);
56 }
57 Pool.wait();
58 ASSERT_EQ(10, checked_in);
59}
60
Mehdi Amini33a7ea42015-12-15 00:59:19 +000061TEST(ThreadPoolTest, Async) {
62 ThreadPool Pool;
63 std::atomic_int i{0};
64 // sleep here just to ensure that the not-equal is correct.
65 Pool.async([&i] {
66 yield();
67 ++i;
68 });
69 Pool.async([&i] { ++i; });
70 ASSERT_NE(2, i.load());
71 Pool.wait();
72 ASSERT_EQ(2, i.load());
73}
74
75TEST(ThreadPoolTest, GetFuture) {
76 ThreadPool Pool;
77 std::atomic_int i{0};
78 // sleep here just to ensure that the not-equal is correct.
79 Pool.async([&i] {
80 yield();
81 ++i;
82 });
83 // Force the future using get()
84 Pool.async([&i] { ++i; }).get();
85 ASSERT_NE(2, i.load());
86 Pool.wait();
87 ASSERT_EQ(2, i.load());
88}
89
90TEST(ThreadPoolTest, PoolDestruction) {
91 // Test that we are waiting on destruction
92 std::atomic_int checked_in{0};
93
94 {
95 ThreadPool Pool;
96 for (size_t i = 0; i < 5; ++i) {
97 Pool.async([&checked_in, i] {
98 yield();
99 ++checked_in;
100 });
101 }
102 ASSERT_EQ(0, checked_in);
103 }
104 ASSERT_EQ(5, checked_in);
105}