From eec849f4b9048019d73260675d1ef2c74987d349 Mon Sep 17 00:00:00 2001 From: sergiu128 Date: Mon, 21 Oct 2024 18:09:58 +0200 Subject: [PATCH] Add writer example --- examples/writer.cpp | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 examples/writer.cpp diff --git a/examples/writer.cpp b/examples/writer.cpp new file mode 100644 index 0000000..0f4f31d --- /dev/null +++ b/examples/writer.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace seqlock; // NOLINT +using namespace std::chrono_literals; // NOLINT + +int main() { // NOLINT + const char* filename = "/shmfiletest42"; + const size_t filesize = util::GetPageSize(); + + util::SharedMemory shm{filename, filesize}; + auto* region = util::Region::Create(shm); + + std::atomic writer_state{0}; // 0: preparing 1: working 2: done + + std::thread writer{[&] { + char from[4096]; + memset(from, 0, 4096); + + writer_state = 1; + for (int i = 0; i < 1024; i++) { + memset(from, i & 127, 4096); // NOLINT + region->Store(from, 4096); + std::this_thread::sleep_for(1ms); + } + + writer_state = 2; + }}; + + std::atomic_flag ok{}; + ok.clear(); + std::thread reader{[&] { + while (writer_state == 0) { + std::this_thread::sleep_for(10ms); + } + + char to[4096]; + memset(to, 0, 4096); + while (writer_state == 1) { + region->Load(to, 4096); + if (to[0] > 0) { + ok.test_and_set(); + for (int i = 0; i < 4095; i++) { + if (to[i] != to[i + 1]) { + std::cout << "invalid load" << std::endl; + std::terminate(); + } + } + } + } + }}; + + writer.join(); + reader.join(); + + if (not ok.test()) { + std::cout << "invalid load" << std::endl; + return EXIT_FAILURE; + } + + std::cout << "load successful" << std::endl; + return EXIT_SUCCESS; +}