• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Function Flow Runtime Serial Queue (C++)
2
3<!--Kit: Function Flow Runtime Kit-->
4<!--Subsystem: Resourceschedule-->
5<!--Owner: @chuchihtung; @yanleo-->
6<!--Designer: @geoffrey_guo; @huangyouzhong-->
7<!--Tester: @lotsof; @sunxuhao-->
8<!--Adviser: @foryourself-->
9
10## Overview
11
12The 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:
13
14- **Queue creation and destruction**: The queue name and priority can be specified during creation. Each queue is equivalent to an independent thread. Tasks in the queue are executed asynchronously compared with user threads.
15- **Task delay**: The `delay` can be set when a task is submitted. The unit is `μs`. The delayed task will be scheduled and executed after `uptime` (submission time + delay time).
16- **Serial scheduling**: Tasks in the same queue are sorted in ascending order of `uptime` and executed in serial mode. Ensure that the next task starts to be executed only after the previous task in the queue is complete.
17- **Task canceling**: You can cancel a task that is not dequeued based on the task handle. The task cannot be canceled if it has been started or completed.
18- **Task waiting**: You can wait for a task to complete based on the task handle. When a specified task is complete, all tasks whose `uptime` is earlier than the specified task in the queue have been executed.
19- **Task priority**: You can set the priority of a single task when submitting the task. Priorities take effect only after a task is dequeued relative to other system loads, and do not affect the serial task order in the same queue. If the task priority is not set, the priority of the queue is inherited by default.
20
21## Example: Asynchronous Log System
22
23The 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.
24
25With 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.
26
27The example simplifies the logic for handling exceptions and ensuring thread security. The code is as follows:
28
29```cpp
30#include <chrono>
31#include <fstream>
32#include <iostream>
33#include <thread>
34#include "ffrt/ffrt.h" // From the OpenHarmony third-party library "@ppd/ffrt"
35
36class Logger {
37public:
38    Logger(const std::string& filename)
39    {
40        // Create a queue.
41        queue_ = std::make_unique<ffrt::queue>("loggerQueue");
42
43        // Open a file in append mode.
44        logFile_.open(filename, std::ios::app);
45        if (!logFile_.is_open()) {
46            throw std::runtime_error("Failed to open log file: " + filename);
47        }
48        std::cout << "Log file opened: " << filename << std::endl;
49    }
50
51    ~Logger() {
52        // Destroy the queue.
53        queue_ = nullptr;
54
55        if (logFile_.is_open()) {
56            logFile_.close();
57            std::cout << "Log file closed" << std::endl;
58        }
59    }
60
61    // Add a log task.
62    void log(const std::string& message) {
63        queue_->submit([this, message] {
64            logFile_ << message << std::endl;
65        });
66    }
67
68private:
69    std::ofstream logFile_;
70    std::unique_ptr<ffrt::queue> queue_;
71};
72
73int main()
74{
75    Logger logger("log.txt");
76
77    // The main thread adds the log task.
78    logger.log("Log message 1");
79    logger.log("Log message 2");
80    logger.log("Log message 3");
81
82    // Simulate the main thread to continue executing other tasks.
83    std::this_thread::sleep_for(std::chrono::seconds(1));
84
85    return 0;
86}
87```
88
89## Available APIs
90
91The main FFRT APIs involved in the preceding example are as follows:
92
93| Name                                                                                                                 | Description          |
94| --------------------------------------------------------------------------------------------------------------------- | -------------- |
95| class [queue](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#queue)   | Queue class.      |
96| [sleep_for](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#sleep_for) | Delays a task for some time.|
97
98> **NOTE**
99>
100> - For details about how to use FFRT C++ APIs, see [Using FFRT C++ APIs](ffrt-development-guideline.md#using-ffrt-c-api-1).
101> - When using FFRT C or C++ APIs, you can use the FFRT C++ API third-party library to simplify the header file inclusion, that is, use the `#include "ffrt/ffrt.h"` header file to include statements.
102
103## Constraints
104
105- **Avoid submitting ultra-long tasks.** The FFRT has a built-in process-level queue task timeout detection mechanism. When the execution time of a serial task exceeds the preset threshold (30 seconds by default), the system prints and reports exception logs and triggers the preset process timeout callback function (if configured).
106- **Use synchronization primitives correctly.** Do not use `std::mutex`, `std::condition_variable`, or `std::recursive_mutex` in the task closure submitted to FFRT. As synchronization primitives in the standard library will occupy the FFRT Worker thread for a long time, you should use the synchronization primitives provided by FFRT: `ffrt::mutex`, `ffrt::condition_variable`, or `ffrt::recursive_mutex`. The usage is the same as that of the standard library.
107- **Manage queues in global variables.** If serial queues are managed in global variables and destroyed with service processes, pay attention to lifecycle decoupling in the test program. When the test is complete, the serial queue needs to be explicitly released. Other resources can be released with global variables. The reason is that global variables are destructed after the main function ends, and the release of serial queues depends on other resources in the FFRT framework, and the resources may have been destroyed.
108