The FFRT serial queue is implemented based on the coroutine scheduling model. It provides efficient message queue functions and supports multiple service scenarios, such as asynchronous communication, mobile data peak clipping, lock-free status and resource management, and architecture decoupling. The following functions are supported:
The following is an example of implementing an asynchronous log system. The main thread submits the log task to the queue, and the background thread obtains the task from the queue and writes the task to the file. It ensures the log sequence and prevents the main thread from being blocked by the file write operation.
With FFRT APIs, you only need to focus on service logic implementation and do not need to pay attention to asynchronous thread management, thread security, and scheduling efficiency.
The example simplifies the logic for handling exceptions and ensuring thread security. The code is as follows:
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include "ffrt/cpp/queue.h"
class Logger {
public:
Logger(const std::string& filename)
{
// Create a queue.
queue_ = std::make_unique<ffrt::queue>("loggerQueue");
// Open a file in append mode.
logFile_.open(filename, std::ios::app);
if (!logFile_.is_open()) {
throw std::runtime_error("Failed to open log file: " + filename);
}
std::cout << "Log file opened: " << filename << std::endl;
}
~Logger() {
// Destroy the queue.
queue_ = nullptr;
if (logFile_.is_open()) {
logFile_.close();
std::cout << "Log file closed" << std::endl;
}
}
// Add a log task.
void log(const std::string& message) {
queue_->submit([this, message] {
logFile_ << message << std::endl;
});
}
private:
std::ofstream logFile_;
std::unique_ptr<ffrt::queue> queue_;
};
int main()
{
Logger logger("log.txt");
// The main thread adds the log task.
logger.log("Log message 1");
logger.log("Log message 2");
logger.log("Log message 3");
// Simulate the main thread to continue executing other tasks.
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}