目录

Function Flow Runtime Serial Queue (C++)

Overview

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:

Example: Asynchronous Log System

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 <thread>
#include "hilog/log.h"
#include "ffrt/ffrt.h" // From the HarmonyOS third-party library "@ppd/ffrt"
#undef LOG_TAG
#define LOG_TAG "SerialCppTag"

class Logger {
public:
    Logger()
    {
        // Create the queue.
        queue_ = std::make_unique<ffrt::queue>("loggerQueue");
        
        logFile_ = stdout;
        OH_LOG_INFO(LOG_APP, "Log file opened");
    }

    ~Logger()
    {
        // Destroy the queue.
        queue_ = nullptr;
        OH_LOG_INFO(LOG_APP, "Log file closed");
    }

    // Add a log task.
    void Log(const std::string& message)
    {
        queue_->submit([this, message] {
            OH_LOG_INFO(LOG_APP, "Writing message %{public}s", message.c_str());
        });
    }

private:
    FILE *logFile_;
    std::unique_ptr<ffrt::queue> queue_;
};

int SerialQueueCppExec()
{
    Logger logger;

    // The main thread adds a log task.
    logger.Log("Log message 1");
    logger.Log("Log message 2");
    logger.Log("Log message 3");

    // Simulate the main thread continuing to execute other tasks.
    std::this_thread::sleep_for(std::chrono::seconds(1));

    return 0;
}

Available APIs

The main FFRT APIs involved in the preceding example are as follows:

Name Description
class queue Queue class.
sleep_for Delays a task for some time.
  • For details about how to use FFRT C++ APIs, see Using FFRT C++ APIs.
  • When using FFRT C or C++ APIs, you can use the FFRT C++ API third-party library to simplify header file inclusion, that is, use the #include "ffrt/ffrt.h" header file inclusion statement.

Constraints