From 8ea3723d0275c96cce95ea42e22fa2488c935c45 Mon Sep 17 00:00:00 2001 From: Otto Moerbeek Date: Mon, 4 Nov 2024 14:44:37 +0100 Subject: [PATCH] Add a unit test checking the ref counts (fails in master) --- pdns/recursordist/test-mtasker.cc | 78 +++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/pdns/recursordist/test-mtasker.cc b/pdns/recursordist/test-mtasker.cc index a4adc08aa7..fd9fd6b9cd 100644 --- a/pdns/recursordist/test-mtasker.cc +++ b/pdns/recursordist/test-mtasker.cc @@ -48,6 +48,84 @@ BOOST_AUTO_TEST_CASE(test_Simple) BOOST_CHECK_EQUAL(events.size(), 0U); } +struct MTKey +{ + int key; + shared_ptr ptr; + + bool operator<(const MTKey& /* b */) const + { + // We don't want explicit PacketID compare here, but always via predicate class below + assert(0); // NOLINT: lib + } +}; + +struct MTKeyCompare +{ + bool operator()(const std::shared_ptr& lhs, const std::shared_ptr& rhs) const + { + return lhs->key < rhs->key; + } +}; + +using KeyMT_t = MTasker, int, MTKeyCompare>; + +// Test the case of #14807 +static void doSomethingKey(void* ptr) +{ + auto* multiTasker = reinterpret_cast(ptr); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast) + auto key = std::make_shared(); + key->key = 12; + key->ptr = std::make_shared(13); + BOOST_CHECK_EQUAL(key.use_count(), 1U); + BOOST_CHECK_EQUAL(key->ptr.use_count(), 1U); + int value = 0; + if (multiTasker->waitEvent(key, &value) == 1) { + g_result = value; + } + BOOST_CHECK_EQUAL(key.use_count(), 1U); + BOOST_CHECK_EQUAL(key->key, 12); + BOOST_REQUIRE(key->ptr != nullptr); + BOOST_CHECK_EQUAL(key->ptr.use_count(), 1U); + BOOST_CHECK_EQUAL(*key->ptr, 13); +} + +BOOST_AUTO_TEST_CASE(test_SharedPointer) +{ + g_result = 0; + KeyMT_t multiTasker; + multiTasker.makeThread(doSomethingKey, &multiTasker); + timeval now{}; + gettimeofday(&now, nullptr); + bool first = true; + int value = 24; + auto key = std::make_shared(); + key->key = 12; + key->ptr = std::make_shared(1); + BOOST_CHECK_EQUAL(key->ptr.use_count(), 1U); + for (;;) { + while (multiTasker.schedule(now)) { + } + + if (first) { + multiTasker.sendEvent(key, &value); + BOOST_CHECK_EQUAL(key.use_count(), 1U); + BOOST_CHECK_EQUAL(key->ptr.use_count(), 1U); + first = false; + } + if (multiTasker.noProcesses()) { + break; + } + } + BOOST_CHECK_EQUAL(g_result, value); + vector> events; + multiTasker.getEvents(events); + BOOST_CHECK_EQUAL(events.size(), 0U); + BOOST_CHECK_EQUAL(key.use_count(), 1U); + BOOST_CHECK_EQUAL(key->ptr.use_count(), 1U); + BOOST_CHECK_EQUAL(*key->ptr, 1); +} + static const size_t stackSize = 8 * 1024; static const size_t headroom = 1536; // Decrease to hit stackoverflow -- 2.47.2