qb
2.0.0.0
C++17 Actor Framework
|
Analyze the file_processor example to learn how QB actors can manage and distribute blocking file I/O tasks asynchronously.
By studying this example, you will understand:
The file_processor example uses three main actor types to achieve its goal:
**Key Event Handling & Logic (on(ReadFileRequest&) and on(WriteFileRequest&)):
This is the core of its non-blocking nature. It captures the necessary request details (filepath, data for write, original requestor ID, request ID) into a lambda and schedules this lambda for execution using qb::io::async::callback([this, captured_request, ...]() { ... });. ```cpp // Simplified from FileWorker::on(ReadFileRequest& request) auto captured_request = request; // Capture needed data auto file_content = std::make_shared<std::vector<char>>(); // Buffer for read
qb::io::async::callback([this, captured_request, file_content]() { if (!this->is_alive()) return; // Actor might have been killed
qb::io::sys::file file_op; bool success = false; qb::string<256> error_message; // — PERFORM BLOCKING FILE I/O — if (file_op.open(captured_request.filepath.c_str(), O_RDONLY) >= 0) { // ... read file into file_content using file_op.read() ... // ... handle potential read errors ... success = true; file_op.close(); } else { error_message = "Failed to open file for reading"; } // — END OF BLOCKING I/O —
// Send response DIRECTLY to the original client actor this->push<ReadFileResponse>(captured_request.requestor, captured_request.filepath.c_str(), file_content, success, error_message.c_str(), captured_request.request_id); notifyAvailable(); // Tell FileManager this worker is free }); ``
async::callback Lambda:**
qb::io::sys::file (open, read/write, close).
ReadFileResponse or WriteFileResponse) containing the result (data read, bytes written, success status, error message), the original request_id, and importantly, the requestor ID from the captured request.
pushes the response event *directly* to the original requestor (captured_request.requestor). This bypasses the FileManager for the response path, reducing load on the manager.
notifyAvailable(), which pushes a WorkerAvailable event (with its own id()) back to the FileManager`.
This example provides a clear blueprint for how to integrate blocking tasks into a QB actor system without sacrificing the benefits of asynchronous processing.
(Next Example Analysis: message_broker Example Analysis**)