util_threadnames_tests.cpp raw
1 // Copyright (c) 2018-present The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include <util/string.h>
6 #include <util/threadnames.h>
7
8 #include <mutex>
9 #include <set>
10 #include <string>
11 #include <thread>
12 #include <vector>
13
14 #include <boost/test/unit_test.hpp>
15
16 using util::ToString;
17
18 BOOST_AUTO_TEST_SUITE(util_threadnames_tests)
19
20 const std::string TEST_THREAD_NAME_BASE = "test_thrd.";
21
22 /**
23 * Run a bunch of threads to all call util::ThreadRename.
24 *
25 * @return the set of name each thread has after attempted renaming.
26 */
27 std::set<std::string> RenameEnMasse(int num_threads)
28 {
29 std::vector<std::thread> threads;
30 std::set<std::string> names;
31 std::mutex lock;
32
33 auto RenameThisThread = [&](int i) {
34 util::ThreadRename(TEST_THREAD_NAME_BASE + ToString(i));
35 std::lock_guard<std::mutex> guard(lock);
36 names.insert(util::ThreadGetInternalName());
37 };
38
39 threads.reserve(num_threads);
40 for (int i = 0; i < num_threads; ++i) {
41 threads.emplace_back(RenameThisThread, i);
42 }
43
44 for (std::thread& thread : threads) thread.join();
45
46 return names;
47 }
48
49 /**
50 * Rename a bunch of threads with the same basename (expect_multiple=true), ensuring suffixes are
51 * applied properly.
52 */
53 BOOST_AUTO_TEST_CASE(util_threadnames_test_rename_threaded)
54 {
55 std::set<std::string> names = RenameEnMasse(100);
56
57 BOOST_CHECK_EQUAL(names.size(), 100U);
58
59 // Names "test_thrd.[n]" should exist for n = [0, 99]
60 for (int i = 0; i < 100; ++i) {
61 BOOST_CHECK(names.contains(TEST_THREAD_NAME_BASE + ToString(i)));
62 }
63
64 }
65
66 BOOST_AUTO_TEST_SUITE_END()
67