clang-tools 10.0.0

ThreadingTests.cpp
Go to the documentation of this file.
1 //===-- ThreadingTests.cpp --------------------------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "Threading.h"
10 #include "gtest/gtest.h"
11 #include <mutex>
12
13 namespace clang {
14 namespace clangd {
15 class ThreadingTest : public ::testing::Test {};
16
17 TEST_F(ThreadingTest, TaskRunner) {
18 const int TasksCnt = 100;
19 // This should be const, but MSVC does not allow to use const vars in lambdas
20 // without capture. On the other hand, clang gives a warning that capture of
21 // const var is not required.
22 // Making it non-const makes both compilers happy.
23 int IncrementsPerTask = 1000;
24
25 std::mutex Mutex;
26 int Counter(0); /* GUARDED_BY(Mutex) */
27 {
28 AsyncTaskRunner Tasks;
29 auto scheduleIncrements = [&]() {
30 for (int TaskI = 0; TaskI < TasksCnt; ++TaskI) {
31 Tasks.runAsync("task", [&Counter, &Mutex, IncrementsPerTask]() {
32 for (int Increment = 0; Increment < IncrementsPerTask; ++Increment) {
33 std::lock_guard<std::mutex> Lock(Mutex);
34 ++Counter;
35 }
36 });
37 }
38 };
39
40 {
41 // Make sure runAsync is not running tasks synchronously on the same
42 // thread by locking the Mutex used for increments.
43 std::lock_guard<std::mutex> Lock(Mutex);
44 scheduleIncrements();
45 }
46
47 Tasks.wait();
48 {
49 std::lock_guard<std::mutex> Lock(Mutex);
50 ASSERT_EQ(Counter, TasksCnt * IncrementsPerTask);
51 }
52
53 {
54 std::lock_guard<std::mutex> Lock(Mutex);
55 Counter = 0;
56 scheduleIncrements();
57 }
58 }
59 // Check that destructor has waited for tasks to finish.
60 std::lock_guard<std::mutex> Lock(Mutex);
61 ASSERT_EQ(Counter, TasksCnt * IncrementsPerTask);
62 }
63 } // namespace clangd
64 } // namespace clang
clang::clangd::AsyncTaskRunner::wait
void wait() const
Definition: Threading.h:110
clang::clangd::TEST_F
TEST_F(BackgroundIndexTest, NoCrashOnErrorFile)
Definition: BackgroundIndexTests.cpp:88
clang::clangd::AsyncTaskRunner::runAsync
void runAsync(const llvm::Twine &Name, llvm::unique_function< void()> Action)
Definition: Threading.cpp:70
clang::clangd::AsyncTaskRunner
Runs tasks on separate (detached) threads and wait for all tasks to finish.
Definition: Threading.h:105
clang::clangd::ThreadingTest
Definition: ThreadingTests.cpp:15
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
Threading.h