审查这个生成式工作器的所有权、失效处理和生命周期行为。
排队的任务不得让 Worker 保活;对象销毁后,状态回调应安全地不执行操作;当前 Job 只能作为非拥有借用暴露。
C++
class Worker : public std::enable_shared_from_this<Worker> {
public:
explicit Worker(TaskQueue& queue) : queue_(queue) {}
void schedule() {
auto keep_alive = shared_from_this();
queue_.push([keep_alive] { keep_alive->run(); });
}
std::function<void()> status_callback() {
auto weak = weak_from_this();
return [weak] { weak.lock()->print_status(); };
}
std::shared_ptr<Job> current_job() {
return std::shared_ptr<Job>(job_.get());
}
void run();
void print_status() const;
private:
TaskQueue& queue_;
std::unique_ptr<Job> job_ = std::make_unique<Job>();
};
生成代码仅作示例,不代表任何特定模型