Files
XCEngine/docs/api/threading/task-group/add-task.md

63 lines
1.4 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.
# TaskGroup::AddTask
```cpp
uint64_t AddTask(std::unique_ptr<ITask> task);
uint64_t AddTask(Callback&& func, TaskPriority priority = TaskPriority::Normal);
```
将任务添加到任务组。支持两种添加方式:传入 ITask 对象或传入回调函数。
**参数:**
- `task` - 唯一指针管理的 ITask 对象
- `func` - 要执行的回调函数
- `priority` - 任务优先级,默认为 `TaskPriority::Normal`
**返回:** 返回分配的任务 ID可用于设置依赖关系
**线程安全:** ✅ 线程安全
**复杂度:** O(1)
**示例:**
```cpp
#include "XCEngine/Threading/TaskGroup.h"
#include "XCEngine/Threading/Task.h"
#include <iostream>
#include <memory>
using namespace XCEngine::Threading;
class MyTask : public ITask {
public:
explicit MyTask(const std::string& name) : m_name(name) {}
void Execute() override {
std::cout << "Executing: " << m_name << "\n";
}
private:
std::string m_name;
};
int main() {
TaskGroup group;
auto task = std::make_unique<MyTask>("DataLoading");
uint64_t taskId = group.AddTask(std::move(task));
uint64_t callbackId = group.AddTask([]() {
std::cout << "Lambda task executing\n";
}, TaskPriority::High);
group.AddDependency(callbackId, taskId);
group.Wait();
return 0;
}
```
## 相关文档
- [TaskGroup 总览](task-group.md) - 返回类总览