使用c语言写一个具有优先级的任务系统
时间: 2023-09-01 11:13:41 浏览: 66
好的,下面是一个简单的具有优先级的任务系统的 C 语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_TASKS 10
typedef struct task {
int id;
int priority;
void (*function)(void);
} Task;
Task taskList[MAX_TASKS];
int numTasks = 0;
void addTask(int id, int priority, void (*function)(void)) {
if (numTasks >= MAX_TASKS) {
printf("Error: Task list is full.\n");
return;
}
taskList[numTasks].id = id;
taskList[numTasks].priority = priority;
taskList[numTasks].function = function;
numTasks++;
}
void runTasks() {
int i, j;
Task temp;
// Sort tasks by priority
for (i = 0; i < numTasks; i++) {
for (j = i + 1; j < numTasks; j++) {
if (taskList[i].priority > taskList[j].priority) {
temp = taskList[i];
taskList[i] = taskList[j];
taskList[j] = temp;
}
}
}
// Execute tasks in order of priority
for (i = 0; i < numTasks; i++) {
printf("Executing task %d...\n", taskList[i].id);
taskList[i].function();
}
}
void task1() {
printf("Task 1 completed.\n");
}
void task2() {
printf("Task 2 completed.\n");
}
void task3() {
printf("Task 3 completed.\n");
}
int main() {
addTask(1, 2, &task1);
addTask(2, 1, &task2);
addTask(3, 3, &task3);
runTasks();
return 0;
}
```
在这个实现中,任务由一个包含任务 ID、优先级和函数指针的结构体 `Task` 表示。我们使用一个静态数组 `taskList` 来存储所有任务,并使用变量 `numTasks` 来跟踪添加到列表中的任务数。
`addTask` 函数用于将新任务添加到列表中。如果任务列表已满,函数将输出一条错误消息并返回。否则,函数将创建一个新的 `Task` 结构体,并将其添加到列表的末尾。
`runTasks` 函数用于执行任务列表中的所有任务。首先,函数将任务按优先级排序,然后按顺序执行每个任务。对于每个任务,函数输出一条消息,告诉用户正在执行哪个任务,然后调用与任务关联的函数指针。
在这个简单的实现中,我们定义了三个简单的任务函数 `task1`、`task2` 和 `task3` 来演示如何使用任务系统。在 `main` 函数中,我们添加了这些任务,并使用 `runTasks` 函数来执行它们。任务 2 的优先级最高,因此它将首先执行。
您可以根据自己的需求修改此示例以实现更复杂的任务系统。希望这可以帮助您开始实现自己的任务系统。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)