text
stringlengths
0
2.2M
TEST(LockFreeRingBuffer, writeReadSequentiallyBackward) {
const int capacity = 256;
const int turns = 4;
LockFreeRingBuffer<int> rb(capacity);
for (unsigned int turn = 0; turn < turns; turn++) {
for (unsigned int write = 0; write < capacity; write++) {
int val = turn * capacity + write;
rb.write(val);
}
LockFreeRingBuffer<int>::Cursor cur = rb.currentHead();
cur.moveBackward(1); /// last write
for (int write = capacity - 1; write >= 0; write--) {
int foo = 0;
ASSERT_TRUE(rb.tryRead(foo, cur));
ASSERT_EQ(turn * capacity + write, foo);
cur.moveBackward();
}
}
}
TEST(LockFreeRingBuffer, readsCanBlock) {
// Start a reader thread, confirm that reading can block
std::atomic<bool> readerHasRun(false);
LockFreeRingBuffer<int> rb(1);
auto cursor = rb.currentHead();
cursor.moveForward(3); // wait for the 4th write
const int sentinel = 0xfaceb00c;
auto reader = std::thread([&]() {
int val = 0;
EXPECT_TRUE(rb.waitAndTryRead(val, cursor));
readerHasRun = true;
EXPECT_EQ(sentinel, val);
});
for (int i = 0; i < 4; i++) {
EXPECT_FALSE(readerHasRun);
int val = sentinel;
rb.write(val);
}
reader.join();
EXPECT_TRUE(readerHasRun);
}
// expose the cursor raw value via a wrapper type
template <typename T, template <typename> class Atom>
uint64_t value(const typename LockFreeRingBuffer<T, Atom>::Cursor& rbcursor) {
typedef typename LockFreeRingBuffer<T, Atom>::Cursor RBCursor;
struct ExposedCursor : RBCursor {
ExposedCursor(const RBCursor& cursor) : RBCursor(cursor) {}
uint64_t value() { return this->ticket; }
};
return ExposedCursor(rbcursor).value();
}
template <template <typename> class Atom>
void runReader(
LockFreeRingBuffer<int, Atom>& rb, std::atomic<int32_t>& writes) {
int32_t idx;
while ((idx = writes--) > 0) {
rb.write(idx);
}
}
template <template <typename> class Atom>
void runWritesNeverFail(int capacity, int writes, int writers) {
using folly::test::DeterministicSchedule;
DeterministicSchedule sched(DeterministicSchedule::uniform(0));
LockFreeRingBuffer<int, Atom> rb(capacity);
std::atomic<int32_t> writes_remaining(writes);
std::vector<std::thread> threads(writers);
for (int i = 0; i < writers; i++) {
threads[i] = DeterministicSchedule::thread(
std::bind(runReader<Atom>, std::ref(rb), std::ref(writes_remaining)));
}
for (auto& thread : threads) {
DeterministicSchedule::join(thread);
}
EXPECT_EQ(writes, (value<int, Atom>)(rb.currentHead()));
}
TEST(LockFreeRingBuffer, writesNeverFail) {
using folly::detail::EmulatedFutexAtomic;
using folly::test::DeterministicAtomic;
runWritesNeverFail<DeterministicAtomic>(1, 100, 4);
runWritesNeverFail<DeterministicAtomic>(10, 100, 4);
runWritesNeverFail<DeterministicAtomic>(100, 1000, 8);
runWritesNeverFail<DeterministicAtomic>(1000, 10000, 16);
runWritesNeverFail<std::atomic>(1, 100, 4);