1 1.1 christos /* 2 1.1 christos * Copyright (c) Meta Platforms, Inc. and affiliates. 3 1.1 christos * All rights reserved. 4 1.1 christos * 5 1.1 christos * This source code is licensed under both the BSD-style license (found in the 6 1.1 christos * LICENSE file in the root directory of this source tree) and the GPLv2 (found 7 1.1 christos * in the COPYING file in the root directory of this source tree). 8 1.1 christos */ 9 1.1 christos #include "utils/ResourcePool.h" 10 1.1 christos 11 1.1 christos #include <gtest/gtest.h> 12 1.1 christos #include <atomic> 13 1.1 christos #include <thread> 14 1.1 christos 15 1.1 christos using namespace pzstd; 16 1.1 christos 17 1.1 christos TEST(ResourcePool, FullTest) { 18 1.1 christos unsigned numCreated = 0; 19 1.1 christos unsigned numDeleted = 0; 20 1.1 christos { 21 1.1 christos ResourcePool<int> pool( 22 1.1 christos [&numCreated] { ++numCreated; return new int{5}; }, 23 1.1 christos [&numDeleted](int *x) { ++numDeleted; delete x; }); 24 1.1 christos 25 1.1 christos { 26 1.1 christos auto i = pool.get(); 27 1.1 christos EXPECT_EQ(5, *i); 28 1.1 christos *i = 6; 29 1.1 christos } 30 1.1 christos { 31 1.1 christos auto i = pool.get(); 32 1.1 christos EXPECT_EQ(6, *i); 33 1.1 christos auto j = pool.get(); 34 1.1 christos EXPECT_EQ(5, *j); 35 1.1 christos *j = 7; 36 1.1 christos } 37 1.1 christos { 38 1.1 christos auto i = pool.get(); 39 1.1 christos EXPECT_EQ(6, *i); 40 1.1 christos auto j = pool.get(); 41 1.1 christos EXPECT_EQ(7, *j); 42 1.1 christos } 43 1.1 christos } 44 1.1 christos EXPECT_EQ(2, numCreated); 45 1.1 christos EXPECT_EQ(numCreated, numDeleted); 46 1.1 christos } 47 1.1 christos 48 1.1 christos TEST(ResourcePool, ThreadSafe) { 49 1.1 christos std::atomic<unsigned> numCreated{0}; 50 1.1 christos std::atomic<unsigned> numDeleted{0}; 51 1.1 christos { 52 1.1 christos ResourcePool<int> pool( 53 1.1 christos [&numCreated] { ++numCreated; return new int{0}; }, 54 1.1 christos [&numDeleted](int *x) { ++numDeleted; delete x; }); 55 1.1 christos auto push = [&pool] { 56 1.1 christos for (int i = 0; i < 100; ++i) { 57 1.1 christos auto x = pool.get(); 58 1.1 christos ++*x; 59 1.1 christos } 60 1.1 christos }; 61 1.1 christos std::thread t1{push}; 62 1.1 christos std::thread t2{push}; 63 1.1 christos t1.join(); 64 1.1 christos t2.join(); 65 1.1 christos 66 1.1 christos auto x = pool.get(); 67 1.1 christos auto y = pool.get(); 68 1.1 christos EXPECT_EQ(200, *x + *y); 69 1.1 christos } 70 1.1 christos EXPECT_GE(2, numCreated); 71 1.1 christos EXPECT_EQ(numCreated, numDeleted); 72 1.1 christos } 73