shared_ptr.cpp (1607B)
1 #include "libshit/shared_ptr.hpp" 2 3 #include "libshit/doctest.hpp" 4 #include "libshit/random.hpp" 5 6 #include <array> 7 #include <thread> 8 #include <vector> 9 10 namespace Libshit::Test 11 { 12 TEST_SUITE_BEGIN("Libshit::SharedPtr"); 13 14 namespace 15 { 16 struct Foo : RefCounted {}; 17 } 18 19 // Skip this test on valgrind on CI. First, valgrind is slow a shit to begin 20 // with then there is the problem that valgrind forces execution onto a single 21 // CPU while thread_concurrency still reports the real CPU count... so the 22 // more cores you have, the slower this test becomes. For example, on my 23 // 4-core + hypertreading (=8 threads) CPU, to run the unoptimized 24 // libshit-tests takes 2 seconds, with valgrind it takes 7.5 minutes. 25 TEST_CASE_TEMPLATE("multithread[no_valgrind]", T, Foo, int) 26 { 27 std::array<Libshit::SmartPtr<T>, 10> ptrs; 28 for (auto& p : ptrs) p = Libshit::MakeSmart<T>(); 29 30 static constexpr const unsigned COUNT = 1000000; 31 auto fun = [&]() 32 { 33 std::array<Libshit::SmartPtr<T>, 10> strong; 34 std::array<Libshit::WeakSmartPtr<T>, 10> weak; 35 Xoshiro128p rnd; 36 37 for (unsigned i = 0; i < COUNT; ++i) 38 if (rnd.Gen<bool>()) 39 strong[rnd.Gen<unsigned, 10>()] = ptrs[rnd.Gen<unsigned, 10>()]; 40 else 41 weak[rnd.Gen<unsigned, 10>()] = ptrs[rnd.Gen<unsigned, 10>()]; 42 }; 43 44 std::vector<std::thread> thrs; 45 for (unsigned i = 0, n = std::thread::hardware_concurrency(); i < n; ++i) 46 thrs.emplace_back(fun); 47 for (auto& t : thrs) t.join(); 48 49 for (auto& p : ptrs) 50 CHECK(p.use_count() == 1); 51 } 52 53 TEST_SUITE_END(); 54 }