C++ · 完整文件
01_basic.cpp
最小完整流程:创建发送入口,接收消息,再结束发送并等待处理完。
examples/01_basic.cpp
123using namespace TwoBufQueue;45int main() try {6 struct CustomData { int Data; };78 //---------------1. Initialization--------------------------------------9 std::size_t count = 0; 10 auto writer = make_writer<Writer<>>();// The producer's writer object.1112 // Consumer callback.13 auto rcvCallback = [&](std::int32_t thread_id, const std::byte* data, std::size_t size) noexcept -> void {14 (void)thread_id; // One writer; thread_id is always 0.15 if (++count <= 3) {16 std::printf("message: len = %.*s\n", static_cast<int>(size), reinterpret_cast<const char*>(data));17 } else {// No fixed payload type: decode according to the application's format.18 int type = 0;19 std::memcpy(&type, data, sizeof(type));20 std::printf("message: len = %d, type = %d\n", static_cast<int>(size), type);21 }22 };2324 ::TwoBufQueue::TwoBufQueue queue(rcvCallback, writer); // Queue that transfers the data.25 26 //---------------2. Producer writes-------------------------------------27 bool written = true;28 for (std::string_view text : {"hello", "TwoBufQueue", "goodbye"})29 written &= writer.write_mem(text.data(), static_cast<std::uint16_t>(text.size()));30 31 // No fixed payload type: the consumer callback decodes the received data using the application's format.32 written &= writer.write(1, 1, static_cast<short>(2)); 33 written &= writer.write(2, CustomData{3}); 3435 //---------------3. Finish----------------------------------------------36 writer.finish(); // The application is responsible for finishing the producer.37 queue.stop(); // Wait until all records are consumed, then stop the threads.3839 //---------------4. Check the result------------------------------------40 example::require(written && count == 5, "write/drain or message count mismatch");41 std::puts("PASS: 5 messages");42} catch (const std::exception& error) { std::fprintf(stderr, "%s\n", error.what()); return 1; }