98 lines
2.9 KiB
C++
98 lines
2.9 KiB
C++
#include "../ConcurrentAppendCollection.h"
|
|
#include "catch/catch.hpp"
|
|
#include <thread>
|
|
|
|
namespace bts {
|
|
|
|
struct Chunk {
|
|
size_t a, b, c, d;
|
|
};
|
|
|
|
TEST_CASE("ConcurrentAppendCollection", "[collection]") {
|
|
SECTION("SEQUENTIAL") {
|
|
ConcurrentAppendCollection<size_t, 5> intvec;
|
|
ConcurrentAppendCollection<Chunk, 5> chunkvec;
|
|
// Insert 9999 elements
|
|
for (size_t x = 0; x < 9999; ++x) {
|
|
intvec.push_back(x);
|
|
chunkvec.push_back({x, x, x, x});
|
|
}
|
|
size_t expected = 0;
|
|
for (const auto &i : intvec) {
|
|
REQUIRE(i == expected);
|
|
++expected;
|
|
}
|
|
REQUIRE(expected == 9999);
|
|
expected = 0;
|
|
for (const auto &i : chunkvec) {
|
|
REQUIRE(i.a == expected);
|
|
REQUIRE(i.b == expected);
|
|
REQUIRE(i.c == expected);
|
|
REQUIRE(i.d == expected);
|
|
++expected;
|
|
}
|
|
REQUIRE(expected == 9999);
|
|
for (size_t x = 0; x < 9999; ++x) {
|
|
REQUIRE(intvec[x] == x);
|
|
REQUIRE(chunkvec[x].a == x);
|
|
REQUIRE(chunkvec[x].b == x);
|
|
REQUIRE(chunkvec[x].c == x);
|
|
REQUIRE(chunkvec[x].d == x);
|
|
}
|
|
|
|
auto iter = intvec.begin();
|
|
REQUIRE(*iter == 0);
|
|
++iter;
|
|
REQUIRE(*iter == 1);
|
|
iter++;
|
|
REQUIRE(*iter == 2);
|
|
--iter;
|
|
REQUIRE(*iter == 1);
|
|
iter--;
|
|
REQUIRE(*iter == 0);
|
|
|
|
REQUIRE(intvec.size() == 9999);
|
|
REQUIRE(chunkvec.size() == 9999);
|
|
}
|
|
SECTION("ONCE MORE, WITH THREADS") {
|
|
const size_t OUTTER = 100;
|
|
const size_t INNER = 1000;
|
|
ConcurrentAppendCollection<Chunk> chunkvec;
|
|
std::thread writer([&]() {
|
|
// write a million elements to the vec
|
|
for (size_t a = 0; a < OUTTER; ++a) {
|
|
for (size_t b = 0; b < INNER; ++b) {
|
|
auto x = 1000 * a + b;
|
|
chunkvec.push_back({x, x, x, x});
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
|
}
|
|
});
|
|
std::vector<std::thread> readers;
|
|
for (size_t x = 0; x < 10; ++x) {
|
|
readers.push_back(std::thread([&]() {
|
|
// read until we have read a million elements
|
|
size_t goal = OUTTER * INNER;
|
|
size_t count = 0;
|
|
while (count != goal) {
|
|
count = 0;
|
|
for (const auto &item : chunkvec) {
|
|
// If theses tests are wrong it may be that item is partially
|
|
// constructed
|
|
REQUIRE(item.a == item.d);
|
|
REQUIRE(item.c == item.d);
|
|
REQUIRE(item.b == item.c);
|
|
REQUIRE(item.a == item.b);
|
|
++count;
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
writer.join();
|
|
for (auto &thread : readers) {
|
|
thread.join();
|
|
}
|
|
}
|
|
}
|
|
|
|
} // namespace bts
|