Files
XCEngine/docs/api/threading/threading-task-system.md

111 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# TaskSystem
**命名空间**: `XCEngine::Threading`
**类型**: `class` (singleton)
**描述**: 并行任务调度系统单例,提供工作窃取式任务队列和并行 for 循环。
## 概述
`TaskSystem` 是 XCEngine 的核心并行任务调度系统。它创建多个工作线程,使用优先级队列和工作窃取算法调度任务。它还提供 `ParallelFor` 方法用于数据级并行,以及主线程任务队列。
## 单例访问
| 方法 | 描述 |
|------|------|
| `static TaskSystem& Get()` | 获取单例实例 |
## 公共方法
### 生命周期
| 方法 | 描述 |
|------|------|
| `void Initialize(const TaskSystemConfig& config)` | 初始化任务系统 |
| `void Shutdown()` | 关闭任务系统 |
### 任务提交
| 方法 | 描述 |
|------|------|
| `uint64_t Submit(std::unique_ptr<ITask> task)` | 提交任务对象 |
| `uint64_t Submit(std::function<void()>&& func, TaskPriority priority = TaskPriority::Normal)` | 提交 lambda 任务 |
### 任务组
| 方法 | 描述 |
|------|------|
| `TaskGroup* CreateTaskGroup()` | 创建任务组 |
| `void DestroyTaskGroup(TaskGroup* group)` | 销毁任务组 |
### 等待
| 方法 | 描述 |
|------|------|
| `void Wait(uint64_t taskId)` | 等待指定任务完成 |
### 信息
| 方法 | 描述 |
|------|------|
| `uint32_t GetWorkerThreadCount() const` | 获取工作线程数量 |
### 并行 for
| 方法 | 描述 |
|------|------|
| `template<typename Func> void ParallelFor(int32_t start, int32_t end, Func&& func)` | 并行执行 for 循环 |
### 主线程
| 方法 | 描述 |
|------|------|
| `void RunOnMainThread(std::function<void()>&& func)` | 将任务提交到主线程执行 |
| `void Update()` | 在主线程中处理主线程队列 |
## 使用示例
```cpp
// 初始化4 个工作线程)
TaskSystemConfig config;
config.workerThreadCount = 4;
TaskSystem::Get().Initialize(config);
// 提交任务
TaskSystem::Get().Submit([]() {
printf("Task 1 running\n");
});
TaskSystem::Get().Submit([]() {
printf("Task 2 running\n");
}, TaskPriority::High);
// 并行 for
TaskSystem::Get().ParallelFor(0, 1000, [](int32_t i) {
// 每个 i 独立处理
process(i);
});
// 主线程任务
TaskSystem::Get().RunOnMainThread([]() {
// 更新 UI 或其他主线程操作
});
// 主循环中调用 Update
while (running) {
TaskSystem::Get().Update(); // 处理主线程任务
// 其他渲染...
}
// 关闭
TaskSystem::Get().Shutdown();
```
## 相关文档
- [ITask](./threading-task.md) - 任务基类
- [LambdaTask](./threading-lambdatask.md) - Lambda 任务
- [TaskGroup](./threading-task-group.md) - 任务组
- [TaskSystemConfig](./threading-tasksystemconfig.md) - 配置