1e41f4b71Sopenharmony_ci# Task
2e41f4b71Sopenharmony_ci
3e41f4b71Sopenharmony_ci
4e41f4b71Sopenharmony_ci## Basic Concepts
5e41f4b71Sopenharmony_ci
6e41f4b71Sopenharmony_ciTasks are the minimum running units that compete for system resources. They can use or wait to use CPUs and use system resources such as memory. They run independently from one another.
7e41f4b71Sopenharmony_ci
8e41f4b71Sopenharmony_ciIn the OpenHarmony kernel, a task represents a thread.
9e41f4b71Sopenharmony_ci
10e41f4b71Sopenharmony_ciTasks for the processes of the same priority in the OpenHarmony kernel are scheduled and run in a unified manner.
11e41f4b71Sopenharmony_ci
12e41f4b71Sopenharmony_ciThe tasks in the kernel use the preemptive scheduling mechanism, either round-robin (RR) scheduling or First In First Out (FIFO) scheduling.
13e41f4b71Sopenharmony_ci
14e41f4b71Sopenharmony_ciTasks are assigned 32 priorities, ranging from **0** (highest) to **31** (lowest).
15e41f4b71Sopenharmony_ci
16e41f4b71Sopenharmony_ciIn the same process, a higher-priority task can preempt resources of a lower-priority task. The lower-priority task can be scheduled only after the higher-priority task is blocked or terminated.
17e41f4b71Sopenharmony_ci
18e41f4b71Sopenharmony_ci**Task States**
19e41f4b71Sopenharmony_ci
20e41f4b71Sopenharmony_ci- Init: The task is being created.
21e41f4b71Sopenharmony_ci
22e41f4b71Sopenharmony_ci- Ready: The task is in the Ready queue and waits for scheduling by the CPU.
23e41f4b71Sopenharmony_ci
24e41f4b71Sopenharmony_ci- Running: The task is running.
25e41f4b71Sopenharmony_ci
26e41f4b71Sopenharmony_ci- Blocked: The task is blocked and suspended. The Blocked states include pending (blocked due to lock, event, or semaphore issues), suspended (active pending), delay (blocked due to delays), and pendtime (blocked by waiting timeout of locks, events, or semaphores).
27e41f4b71Sopenharmony_ci
28e41f4b71Sopenharmony_ci- Exit: The task is complete and waits for the parent task to reclaim its control block resources.
29e41f4b71Sopenharmony_ci
30e41f4b71Sopenharmony_ci  **Figure 1** Task state transition
31e41f4b71Sopenharmony_ci
32e41f4b71Sopenharmony_ci  ![](figures/task-state-transition.png "task-state-transition")
33e41f4b71Sopenharmony_ci
34e41f4b71Sopenharmony_ci**Task State Transition**
35e41f4b71Sopenharmony_ci
36e41f4b71Sopenharmony_ci- Init→Ready:
37e41f4b71Sopenharmony_ci  When a task is created, the task obtains the control block and enters the Init state (initialization). After the initialization is complete, the task is inserted into the scheduling queue and enters the Ready state.
38e41f4b71Sopenharmony_ci
39e41f4b71Sopenharmony_ci- Ready→Running:
40e41f4b71Sopenharmony_ci  When a task switching is triggered, the task with the highest priority in the Ready queue is executed and enters the Running state. Then, this task is deleted from the Ready queue.
41e41f4b71Sopenharmony_ci
42e41f4b71Sopenharmony_ci- Running→Blocked:
43e41f4b71Sopenharmony_ci  When a running task is blocked (for example, is pended, delayed, or reading semaphores), its state changes from Running to Blocked. Then, a task switching is triggered to run the task with the highest priority in the Ready queue.
44e41f4b71Sopenharmony_ci
45e41f4b71Sopenharmony_ci- Blocked→Ready:
46e41f4b71Sopenharmony_ci  After the blocked task is restored (the task is restored, the delay times out, the semaphore reading times out, or the semaphore is read), the task is added to the Ready queue and will change from the Blocked state to the Ready state.
47e41f4b71Sopenharmony_ci
48e41f4b71Sopenharmony_ci- Ready→Blocked:
49e41f4b71Sopenharmony_ci  When a task in the Ready state is blocked (suspended), the task changes to the Blocked state and is deleted from the Ready queue. The blocked task will not be scheduled until it is recovered.
50e41f4b71Sopenharmony_ci
51e41f4b71Sopenharmony_ci- Running→Ready:
52e41f4b71Sopenharmony_ci  When a task with a higher priority is created or recovered, tasks will be scheduled. The task with the highest priority in the Ready queue changes to the Running state. The originally running task changes to the Ready state and is added to the Ready queue.
53e41f4b71Sopenharmony_ci
54e41f4b71Sopenharmony_ci- Running→Exit:
55e41f4b71Sopenharmony_ci  When a running task is complete, it changes to the Exit state. If the task has a detach attribute (set by **LOS_TASK_STATUS_DETACHED** in **los_task.h**), it will be destroyed directly.
56e41f4b71Sopenharmony_ci
57e41f4b71Sopenharmony_ci
58e41f4b71Sopenharmony_ci## Working Principles
59e41f4b71Sopenharmony_ci
60e41f4b71Sopenharmony_ciThe OpenHarmony task management module provides the following functions: creating, delaying, suspending, and restoring tasks, locking and unlocking task scheduling, and querying task control block information by ID.
61e41f4b71Sopenharmony_ci
62e41f4b71Sopenharmony_ciWhen a user creates a task, the system initializes the task stack and presets the context. The system places the task entry function in the corresponding position so that the function can be executed when the task enters the running state for the first time.
63e41f4b71Sopenharmony_ci
64e41f4b71Sopenharmony_ci
65e41f4b71Sopenharmony_ci## Development Guidelines
66e41f4b71Sopenharmony_ci
67e41f4b71Sopenharmony_ci
68e41f4b71Sopenharmony_ci### Available APIs
69e41f4b71Sopenharmony_ci
70e41f4b71Sopenharmony_ci**Table 1** APIs for creating and deleting a task
71e41f4b71Sopenharmony_ci
72e41f4b71Sopenharmony_ci| API            | Description                                                    |
73e41f4b71Sopenharmony_ci| ------------------ | ------------------------------------------------------------ |
74e41f4b71Sopenharmony_ci| LOS_TaskCreate     | Creates a task. If the priority of the created task is higher than that of the task in running and task scheduling is not locked, the task will be scheduled to run. |
75e41f4b71Sopenharmony_ci| LOS_TaskCreateOnly | Creates a task and blocks it. The task will not be added to the Ready queue unless it is resumed.            |
76e41f4b71Sopenharmony_ci| LOS_TaskDelete     | Deletes a task and reclaims the resources consumed by the task control block and task stack.        |
77e41f4b71Sopenharmony_ci
78e41f4b71Sopenharmony_ci**Table 2** APIs for controlling task status
79e41f4b71Sopenharmony_ci
80e41f4b71Sopenharmony_ci| API         | Description                                                    |
81e41f4b71Sopenharmony_ci| --------------- | ------------------------------------------------------------ |
82e41f4b71Sopenharmony_ci| LOS_TaskResume  | Resumes a suspended task.                                              |
83e41f4b71Sopenharmony_ci| LOS_TaskSuspend | Suspends a task. The suspended task will be removed from the Ready queue.                |
84e41f4b71Sopenharmony_ci| LOS_TaskJoin    | Blocks the current task until the specified task is complete, and reclaims its resources.              |
85e41f4b71Sopenharmony_ci| LOS_TaskDetach  | Changes the task attribute from **joinable** to **detach**. When a task of the **detach** attribute is complete, the task control block resources will be automatically reclaimed.|
86e41f4b71Sopenharmony_ci| LOS_TaskDelay   | Delays the current task for the specified time (number of ticks).            |
87e41f4b71Sopenharmony_ci| LOS_TaskYield   | Moves the current task from the queue of the tasks with the same priority to the end of the Ready queue.|
88e41f4b71Sopenharmony_ci
89e41f4b71Sopenharmony_ci**Table 3** APIs for task scheduling
90e41f4b71Sopenharmony_ci
91e41f4b71Sopenharmony_ci| API              | Description                                                    |
92e41f4b71Sopenharmony_ci| -------------------- | ------------------------------------------------------------ |
93e41f4b71Sopenharmony_ci| LOS_TaskLock         | Locks task scheduling to prevent task switching.                                  |
94e41f4b71Sopenharmony_ci| LOS_TaskUnlock       | Unlocks task scheduling. After that, the task lock count decrements by 1. If a task is locked multiple times, the task can be scheduled only when the number of locks is reduced to 0. |
95e41f4b71Sopenharmony_ci| LOS_GetTaskScheduler | Obtains the scheduling policy of a task.                                      |
96e41f4b71Sopenharmony_ci| LOS_SetTaskScheduler | Sets the scheduling parameters, including the priority and scheduling policy, for a task.                |
97e41f4b71Sopenharmony_ci| LOS_Schedule         | Triggers active task scheduling.                                          |
98e41f4b71Sopenharmony_ci
99e41f4b71Sopenharmony_ci**Table 4** APIs for obtaining task information
100e41f4b71Sopenharmony_ci
101e41f4b71Sopenharmony_ci| API                  | Description                |
102e41f4b71Sopenharmony_ci| ------------------------ | ------------------------ |
103e41f4b71Sopenharmony_ci| LOS_CurTaskIDGet         | Obtains the ID of the current task.        |
104e41f4b71Sopenharmony_ci| LOS_TaskInfoGet          | Obtains task information.      |
105e41f4b71Sopenharmony_ci| LOS_GetSystemTaskMaximum | Obtains the maximum number of tasks supported by the system.|
106e41f4b71Sopenharmony_ci
107e41f4b71Sopenharmony_ci**Table 5** APIs for managing task priorities
108e41f4b71Sopenharmony_ci
109e41f4b71Sopenharmony_ci| API           | Description                      |
110e41f4b71Sopenharmony_ci| ----------------- | ------------------------------ |
111e41f4b71Sopenharmony_ci| LOS_CurTaskPriSet | Sets a priority for the current task.|
112e41f4b71Sopenharmony_ci| LOS_TaskPriSet    | Sets a priority for a task.          |
113e41f4b71Sopenharmony_ci| LOS_TaskPriGet    | Obtains the priority of a task.          |
114e41f4b71Sopenharmony_ci
115e41f4b71Sopenharmony_ci**Table 6** APIs for setting CPU pinning
116e41f4b71Sopenharmony_ci
117e41f4b71Sopenharmony_ci| API            | Description                                   |
118e41f4b71Sopenharmony_ci| ------------------ | ------------------------------------------- |
119e41f4b71Sopenharmony_ci| LOS_TaskCpuAffiSet | Binds a task to the specified CPU core. This API is used only in multi-core CPUs.|
120e41f4b71Sopenharmony_ci| LOS_TaskCpuAffiGet | Obtains information about the core binding of a task. This API is used only in multi-core CPUs.     |
121e41f4b71Sopenharmony_ci
122e41f4b71Sopenharmony_ci
123e41f4b71Sopenharmony_ci
124e41f4b71Sopenharmony_ci### How to Develop
125e41f4b71Sopenharmony_ci
126e41f4b71Sopenharmony_ciThe typical task development process is as follows:
127e41f4b71Sopenharmony_ci
128e41f4b71Sopenharmony_ci1. Call **LOS_TaskCreate** to create a task.
129e41f4b71Sopenharmony_ci   - Specify the execution entry function for the task.
130e41f4b71Sopenharmony_ci   - Specifies the task name.
131e41f4b71Sopenharmony_ci   - Specify the task stack size.
132e41f4b71Sopenharmony_ci   - Specify the priority of the task.
133e41f4b71Sopenharmony_ci   - Specify the task attribute, which can be **LOS_TASK_ATTR_JOINABLE** or **LOS_TASK_STATUS_DETACHED**.
134e41f4b71Sopenharmony_ci   - Specify the task-core binding attribute for multi-core environment.
135e41f4b71Sopenharmony_ci
136e41f4b71Sopenharmony_ci2. Run the service code to implement task scheduling.
137e41f4b71Sopenharmony_ci
138e41f4b71Sopenharmony_ci3. Reclaim resources when the task is complete. If the task attribute is **LOS_TASK_STATUS_DETACHED**, the task resources are automatically reclaimed. If the task attribute is **LOS_TASK_ATTR_JOINABLE**, call **LOS_TaskJoin** to reclaim task resources. The default task attribute is **LOS_TASK_STATUS_DETACHED**.
139e41f4b71Sopenharmony_ci
140e41f4b71Sopenharmony_ci> **NOTE**
141e41f4b71Sopenharmony_ci> 
142e41f4b71Sopenharmony_ci> - The kernel mode has the highest permission and can operate tasks in any process.
143e41f4b71Sopenharmony_ci>
144e41f4b71Sopenharmony_ci> - If a task is created after a user-mode process enters the kernel mode by a system call, the task belongs to a KProcess not a user-mode process.
145e41f4b71Sopenharmony_ci
146e41f4b71Sopenharmony_ci
147e41f4b71Sopenharmony_ci### Development Example
148e41f4b71Sopenharmony_ci
149e41f4b71Sopenharmony_ciThe sample code is as follows. You can add the test function of the sample code to **TestTaskEntry** in **kernel/liteos_a/testsuites/kernel/src /osTest.c** for testing
150e41f4b71Sopenharmony_ci
151e41f4b71Sopenharmony_ci
152e41f4b71Sopenharmony_ci```c
153e41f4b71Sopenharmony_ciUINT32 g_taskLoID;
154e41f4b71Sopenharmony_ciUINT32 g_taskHiID;
155e41f4b71Sopenharmony_ci#define TSK_PRIOR_HI 4
156e41f4b71Sopenharmony_ci#define TSK_PRIOR_LO 5
157e41f4b71Sopenharmony_ciUINT32 ExampleTaskHi(VOID)
158e41f4b71Sopenharmony_ci{
159e41f4b71Sopenharmony_ci    UINT32 ret;
160e41f4b71Sopenharmony_ci    PRINTK("Enter TaskHi Handler.\n");
161e41f4b71Sopenharmony_ci    /* Delay the task for 2 ticks. The task is suspended, and the remaining task with the highest priority (g_taskLoID) will be executed. */
162e41f4b71Sopenharmony_ci    ret = LOS_TaskDelay(2);
163e41f4b71Sopenharmony_ci    if (ret != LOS_OK) {
164e41f4b71Sopenharmony_ci        PRINTK("Delay Task Failed.\n");
165e41f4b71Sopenharmony_ci        return LOS_NOK;
166e41f4b71Sopenharmony_ci    }
167e41f4b71Sopenharmony_ci    /* After 2 ticks elapse, the task is resumed and executed. */
168e41f4b71Sopenharmony_ci    PRINTK("TaskHi LOS_TaskDelay Done.\n");
169e41f4b71Sopenharmony_ci    /* Suspend the task. */
170e41f4b71Sopenharmony_ci    ret = LOS_TaskSuspend(g_taskHiID);
171e41f4b71Sopenharmony_ci    if (ret != LOS_OK) {
172e41f4b71Sopenharmony_ci        PRINTK("Suspend TaskHi Failed.\n");
173e41f4b71Sopenharmony_ci        return LOS_NOK;
174e41f4b71Sopenharmony_ci    }
175e41f4b71Sopenharmony_ci    PRINTK("TaskHi LOS_TaskResume Success.\n");
176e41f4b71Sopenharmony_ci    return LOS_OK;
177e41f4b71Sopenharmony_ci}
178e41f4b71Sopenharmony_ci
179e41f4b71Sopenharmony_ci/* Entry function of the low-priority task. */
180e41f4b71Sopenharmony_ciUINT32 ExampleTaskLo(VOID)
181e41f4b71Sopenharmony_ci{
182e41f4b71Sopenharmony_ci    UINT32 ret;
183e41f4b71Sopenharmony_ci    PRINTK("Enter TaskLo Handler.\n");
184e41f4b71Sopenharmony_ci    /* Delay the task for 2 ticks. The task is suspended, and the remaining task with the highest priority (background task) will be executed. */
185e41f4b71Sopenharmony_ci    ret = LOS_TaskDelay(2);
186e41f4b71Sopenharmony_ci    if (ret != LOS_OK) {
187e41f4b71Sopenharmony_ci        PRINTK("Delay TaskLo Failed.\n");
188e41f4b71Sopenharmony_ci        return LOS_NOK;
189e41f4b71Sopenharmony_ci    }
190e41f4b71Sopenharmony_ci    PRINTK("TaskHi LOS_TaskSuspend Success.\n");
191e41f4b71Sopenharmony_ci    /* Resume the suspended task g_taskHiID. */
192e41f4b71Sopenharmony_ci    ret = LOS_TaskResume(g_taskHiID);
193e41f4b71Sopenharmony_ci    if (ret != LOS_OK) {
194e41f4b71Sopenharmony_ci        PRINTK("Resume TaskHi Failed.\n");
195e41f4b71Sopenharmony_ci        return LOS_NOK;
196e41f4b71Sopenharmony_ci    }
197e41f4b71Sopenharmony_ci    PRINTK("TaskHi LOS_TaskDelete Success.\n");
198e41f4b71Sopenharmony_ci    return LOS_OK;
199e41f4b71Sopenharmony_ci}
200e41f4b71Sopenharmony_ci/* Create two tasks with different priorities in the task test entry function. */
201e41f4b71Sopenharmony_ciUINT32 ExampleTaskCaseEntry(VOID)
202e41f4b71Sopenharmony_ci{
203e41f4b71Sopenharmony_ci    UINT32 ret;
204e41f4b71Sopenharmony_ci    TSK_INIT_PARAM_S initParam = {0};
205e41f4b71Sopenharmony_ci
206e41f4b71Sopenharmony_ci    /* Lock task scheduling. */
207e41f4b71Sopenharmony_ci    LOS_TaskLock();
208e41f4b71Sopenharmony_ci    PRINTK("LOS_TaskLock() Success!\n");
209e41f4b71Sopenharmony_ci    /* Parameters used to initialize the high-priority task, the resources of which can be reclaimed by LOS_TaskJoin. */
210e41f4b71Sopenharmony_ci    initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskHi;
211e41f4b71Sopenharmony_ci    initParam.usTaskPrio = TSK_PRIOR_HI;
212e41f4b71Sopenharmony_ci    initParam.pcName = "HIGH_NAME";
213e41f4b71Sopenharmony_ci    initParam.uwStackSize = LOS_TASK_MIN_STACK_SIZE;
214e41f4b71Sopenharmony_ci    initParam.uwResved   = LOS_TASK_ATTR_JOINABLE;
215e41f4b71Sopenharmony_ci
216e41f4b71Sopenharmony_ci    /* Create a task with higher priority. The task will not be executed immediately after being created, because task scheduling is locked. */
217e41f4b71Sopenharmony_ci    ret = LOS_TaskCreate(&g_taskHiID, &initParam);
218e41f4b71Sopenharmony_ci    if (ret != LOS_OK) {
219e41f4b71Sopenharmony_ci        LOS_TaskUnlock();
220e41f4b71Sopenharmony_ci        PRINTK("ExampleTaskHi create Failed! ret=%d\n", ret);
221e41f4b71Sopenharmony_ci        return LOS_NOK;
222e41f4b71Sopenharmony_ci    }
223e41f4b71Sopenharmony_ci    PRINTK("ExampleTaskHi create Success!\n");
224e41f4b71Sopenharmony_ci
225e41f4b71Sopenharmony_ci    /* Parameters used to initialize the low-priority task, which will be automatically destroyed after the task is complete. */
226e41f4b71Sopenharmony_ci    initParam.pfnTaskEntry = (TSK_ENTRY_FUNC)ExampleTaskLo;
227e41f4b71Sopenharmony_ci    initParam.usTaskPrio = TSK_PRIOR_LO;
228e41f4b71Sopenharmony_ci    initParam.pcName = "LOW_NAME";
229e41f4b71Sopenharmony_ci    initParam.uwStackSize = LOS_TASK_MIN_STACK_SIZE;
230e41f4b71Sopenharmony_ci    initParam.uwResved   = LOS_TASK_STATUS_DETACHED;
231e41f4b71Sopenharmony_ci
232e41f4b71Sopenharmony_ci    /* Create a low-priority task. The task will not be executed immediately after being created, because task scheduling is locked. */
233e41f4b71Sopenharmony_ci    ret = LOS_TaskCreate(&g_taskLoID, &initParam);
234e41f4b71Sopenharmony_ci    if (ret!= LOS_OK) {
235e41f4b71Sopenharmony_ci        LOS_TaskUnlock();
236e41f4b71Sopenharmony_ci        PRINTK("ExampleTaskLo create Failed!\n");
237e41f4b71Sopenharmony_ci        return LOS_NOK;
238e41f4b71Sopenharmony_ci    }
239e41f4b71Sopenharmony_ci    PRINTK("ExampleTaskLo create Success!\n");
240e41f4b71Sopenharmony_ci
241e41f4b71Sopenharmony_ci    /* Unlock task scheduling. The task with the highest priority in the Ready queue will be executed. */
242e41f4b71Sopenharmony_ci    LOS_TaskUnlock();
243e41f4b71Sopenharmony_ci    ret = LOS_TaskJoin(g_taskHiID, NULL);
244e41f4b71Sopenharmony_ci    if (ret != LOS_OK) {
245e41f4b71Sopenharmony_ci        PRINTK("Join ExampleTaskHi Failed!\n");
246e41f4b71Sopenharmony_ci    } else {
247e41f4b71Sopenharmony_ci        PRINTK("Join ExampleTaskHi Success!\n");
248e41f4b71Sopenharmony_ci    }
249e41f4b71Sopenharmony_ci    while(1){};
250e41f4b71Sopenharmony_ci    return LOS_OK;
251e41f4b71Sopenharmony_ci}
252e41f4b71Sopenharmony_ci```
253e41f4b71Sopenharmony_ci
254e41f4b71Sopenharmony_ciThe development is successful if the return result is as follows:
255e41f4b71Sopenharmony_ci
256e41f4b71Sopenharmony_ci
257e41f4b71Sopenharmony_ci```
258e41f4b71Sopenharmony_ciLOS_TaskLock() Success!
259e41f4b71Sopenharmony_ciExampleTaskHi create Success!
260e41f4b71Sopenharmony_ciExampleTaskLo create Success!
261e41f4b71Sopenharmony_ciEnter TaskHi Handler.
262e41f4b71Sopenharmony_ciEnter TaskLo Handler.
263e41f4b71Sopenharmony_ciTaskHi LOS_TaskDelay Done.
264e41f4b71Sopenharmony_ciTaskHi LOS_TaskSuspend Success.
265e41f4b71Sopenharmony_ciTaskHi LOS_TaskResume Success.
266e41f4b71Sopenharmony_ciTaskHi LOS_TaskDelete Success.
267e41f4b71Sopenharmony_ciJoin ExampleTaskHi Success!
268e41f4b71Sopenharmony_ci```
269