ObjectPool/main.cpp

84 lines
2.6 KiB
C++

#include "ObjectPool.h"
#include <cassert>
// this is a simple wrapper for gtest, you can move these tests to your gtests
#define TEST(a,b)
#define EXPECT_EQ(a__,b__) assert(a__ == b__);
#define EXPECT_NE(a__,b__) assert(a__ != b__);
#define EXPECT_TRUE(a__) assert(a__);
#define EXPECT_TRUE(a__) assert(a__);
#define EXPECT_FALSE(a__) assert(!a__);
int main() {
TEST(Util, ObjectPool_stress_test)
{
std::size_t poolSize = 100;
std::size_t num_threads = 1000;
std::vector<std::unique_ptr<std::thread>> threads(num_threads);
const int factor = 10;
ObjectPool<int> p(poolSize, [](std::size_t z) { return factor * z; });
for (std::unique_ptr<std::thread>& t : threads) {
t.reset(new std::thread([&p]() {
auto o = p.borrowObj();
*o.getObj() = *o.getObj() + 1;
}));
}
for (std::unique_ptr<std::thread>& t : threads) {
t->join();
}
int expectedSum = num_threads; // every thread adds 1 to the sum
int sum = 0;
for (std::size_t i = 0; i < poolSize; i++) {
expectedSum += factor * i; // initial value in pool member initializer
sum += *p.borrowObj().getObj();
}
EXPECT_EQ(sum, expectedSum);
}
TEST(Util, ObjectPool_try_borrow)
{
std::size_t poolSize = 4;
const int factor = 10;
ObjectPool<int> p(poolSize, [](std::size_t z) { return factor * z; });
bool success = false;
EXPECT_EQ(p.getAvailableObjectsCount(), 4);
BorrowedObject<int> o1 = p.try_borrowObj(success);
EXPECT_TRUE(success);
EXPECT_EQ(p.getAvailableObjectsCount(), 3);
EXPECT_NE(o1.getObj(), nullptr);
BorrowedObject<int> o2 = p.try_borrowObj(success);
EXPECT_EQ(p.getAvailableObjectsCount(), 2);
EXPECT_TRUE(success);
EXPECT_NE(o2.getObj(), nullptr);
BorrowedObject<int> o3 = p.try_borrowObj(success);
EXPECT_EQ(p.getAvailableObjectsCount(), 1);
EXPECT_TRUE(success);
EXPECT_NE(o3.getObj(), nullptr);
BorrowedObject<int> o4 = p.try_borrowObj(success);
EXPECT_EQ(p.getAvailableObjectsCount(), 0);
EXPECT_TRUE(success);
EXPECT_NE(o4.getObj(), nullptr);
BorrowedObject<int> o5 = p.try_borrowObj(success);
EXPECT_FALSE(success);
EXPECT_EQ(o5.getObj(), nullptr);
o5.returnObj();
EXPECT_EQ(p.getAvailableObjectsCount(), 0);
o4.returnObj();
EXPECT_EQ(p.getAvailableObjectsCount(), 1);
}
}