• 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```c
30#include <stdio.h>
31#include <stdlib.h>
32#include <string.h>
33#include <unistd.h>
34#include "ffrt/ffrt.h" // From the OpenHarmony third-party library "@ppd/ffrt"
35
36typedef struct {
37    FILE *logFile;          // Pointer to a log file.
38    ffrt_queue_t queue;     // Task queue.
39} logger_t;
40
41// Global logger variable.
42logger_t* g_logger = NULL;
43
44// Initialize the log system.
45logger_t *logger_create(const char *filename)
46{
47    logger_t *logger = (logger_t *)malloc(sizeof(logger_t));
48    if (!logger) {
49        perror("Failed to allocate memory for logger_t");
50        return NULL;
51    }
52
53    // Open the log file.
54    logger->logFile = fopen(filename, "a");
55    if (!logger->logFile) {
56        perror("Failed to open log file");
57        free(logger);
58        return NULL;
59    }
60    printf("Log file opened: %s\n", filename);
61
62    // Create a task queue.
63    logger->queue = ffrt_queue_create(ffrt_queue_serial, "logger_queue_c", NULL);
64    if (!logger->queue) {
65        perror("Failed to create queue");
66        fclose(logger->logFile);
67        free(logger);
68        return NULL;
69    }
70
71    return logger;
72}
73
74// Destroy the log system.
75void logger_destroy(logger_t *logger)
76{
77    if (logger) {
78        // Destroy the queue.
79        if (logger->queue) {
80            ffrt_queue_destroy(logger->queue);
81        }
82
83        // Close the log file.
84        if (logger->logFile) {
85            fclose(logger->logFile);
86            printf("Log file closed\n");
87        }
88
89        free(logger);
90    }
91}
92
93// Log task.
94void write_task(void *arg)
95{
96    char *message = (char *)arg;
97    if (g_logger && g_logger->logFile) {
98        fprintf(g_logger->logFile, "%s\n", message);
99        fflush(g_logger->logFile);
100    }
101
102    free(message);
103}
104
105// Add a log task.
106void logger_log(logger_t *logger, const char *message)
107{
108    if (!logger || !logger->queue) {
109        return;
110    }
111
112    // Copy the message string.
113    char *messageCopy = strdup(message);
114    if (!messageCopy) {
115        perror("Failed to allocate memory for message");
116        return;
117    }
118
119    ffrt_queue_submit_f(logger->queue, write_task, messageCopy, NULL);
120}
121
122int main()
123{
124    // Initialize the global logger.
125    g_logger = logger_create("log_c.txt");
126    if (!g_logger) {
127        return -1;
128    }
129
130    // Use the global logger to add a log task.
131    logger_log(g_logger, "Log message 1");
132    logger_log(g_logger, "Log message 2");
133    logger_log(g_logger, "Log message 3");
134
135    // Simulate the main thread to continue executing other tasks.
136    sleep(1);
137
138    // Destroy the global logger.
139    logger_destroy(g_logger);
140    g_logger = NULL;
141    return 0;
142}
143```
144
145## Available APIs
146
147The main FFRT APIs involved in the preceding example are as follows:
148
149| Name                                                              | Description                |
150| ------------------------------------------------------------------ | -------------------- |
151| [ffrt_queue_create](ffrt-api-guideline-c.md#ffrt_queue_t)     | Creates a queue.          |
152| [ffrt_queue_destroy](ffrt-api-guideline-c.md#ffrt_queue_t)   | Destroys a queue.          |
153| [ffrt_queue_submit_f](ffrt-api-guideline-c.md#ffrt_queue_t) | Submits a task to a queue.|
154
155> **NOTE**
156>
157> - For details about how to use FFRT C++ APIs, see [Using FFRT C++ APIs](ffrt-development-guideline.md#using-ffrt-c-api-1).
158> - 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.
159
160## Constraints
161
162- **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).
163- **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.
164- **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.
165