Magnet 库教程与命名规范指南
目录
1. 基础入门:创建第一个 Magnet 多线程任务
步骤说明
- 定义任务类
继承mag::Control
并重写decide()
和action()
:#include "Control.hpp" class HelloWorldTask : public mag::Control { public: bool decide() override { return islifing(); // 存活即触发 } void action() override { std::cout << "Hello, Magnet!" << std::endl; destroy(); // 执行后终止 } };
启动任务
使用 mag_update 注册任务:
int main() {
HelloWorldTask task;
mag::mag_update(task);
while (mag::cn > 0) {} // 等待完成
return 0;
}
- 生命周期管理:线程的启动与终止
核心方法
destroy():手动终止线程
class TimeoutTask : public mag::Control {
std::atomic<int> count{0};
public:
bool decide() override {
return count++ < 5; // 执行 5 次后终止
}
void action() override {
std::cout << "Count: " << count << std::endl;
if (count >= 5) destroy();
}
};
自动终止机制
无