|
| 1 | +// Copyright (c) 2018 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/threadnames.h> |
| 6 | +#include <test/setup_common.h> |
| 7 | + |
| 8 | +#include <thread> |
| 9 | +#include <vector> |
| 10 | +#include <set> |
| 11 | +#include <mutex> |
| 12 | + |
| 13 | +#if defined(HAVE_CONFIG_H) |
| 14 | +#include <config/bitcoin-config.h> |
| 15 | +#endif |
| 16 | + |
| 17 | +#include <boost/test/unit_test.hpp> |
| 18 | + |
| 19 | +BOOST_FIXTURE_TEST_SUITE(util_threadnames_tests, BasicTestingSetup) |
| 20 | + |
| 21 | +const std::string TEST_THREAD_NAME_BASE = "test_thread."; |
| 22 | + |
| 23 | +/** |
| 24 | + * Run a bunch of threads to all call util::ThreadRename. |
| 25 | + * |
| 26 | + * @return the set of name each thread has after attempted renaming. |
| 27 | + */ |
| 28 | +std::set<std::string> RenameEnMasse(int num_threads) |
| 29 | +{ |
| 30 | + std::vector<std::thread> threads; |
| 31 | + std::set<std::string> names; |
| 32 | + std::mutex lock; |
| 33 | + |
| 34 | + auto RenameThisThread = [&](int i) { |
| 35 | + util::ThreadRename(TEST_THREAD_NAME_BASE + std::to_string(i)); |
| 36 | + std::lock_guard<std::mutex> guard(lock); |
| 37 | + names.insert(util::ThreadGetInternalName()); |
| 38 | + }; |
| 39 | + |
| 40 | + for (int i = 0; i < num_threads; ++i) { |
| 41 | + threads.push_back(std::thread(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 | + BOOST_CHECK_EQUAL(util::ThreadGetInternalName(), ""); |
| 56 | + |
| 57 | +#if !defined(HAVE_THREAD_LOCAL) |
| 58 | + // This test doesn't apply to platforms where we don't have thread_local. |
| 59 | + return; |
| 60 | +#endif |
| 61 | + |
| 62 | + std::set<std::string> names = RenameEnMasse(100); |
| 63 | + |
| 64 | + BOOST_CHECK_EQUAL(names.size(), 100); |
| 65 | + |
| 66 | + // Names "test_thread.[n]" should exist for n = [0, 99] |
| 67 | + for (int i = 0; i < 100; ++i) { |
| 68 | + BOOST_CHECK(names.find(TEST_THREAD_NAME_BASE + std::to_string(i)) != names.end()); |
| 69 | + } |
| 70 | + |
| 71 | +} |
| 72 | + |
| 73 | +BOOST_AUTO_TEST_SUITE_END() |
0 commit comments