gpt4 book ai didi

c++ - 作业/任务消耗队列,自删除项目的有效案例?

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:22 25 4
gpt4 key购买 nike

self 删除(或从容器中 self 删除)通常被认为是一种不好的做法(有充分的理由),但我想知道 self 删除是否是以下情况的合法方法:

我们有一个任务队列,一个进程使用队列(queue.front() 任务)。

  • 对于某些任务(Guaranteed Tasks),执行是有保证的,只要没有完成,它就一直排在队列的前面。一旦成功,它就会被删除,queue.pop()。

  • 对于其他一些任务(临时 任务),我们不关心是否完成,我们尝试并在失败或成功时弹出。

这可能是完全过度优化,但我不喜欢在阅读前端任务时进行测试。因为我们已经知道当我们将任务推送到队列中时,行为应该是什么。因此,清空队列时的切换/分支在我看来是设计失败。

这是一个非常简单的单个文件示例,您可以复制/粘贴和编译:

#include <iostream>
#include <queue>
#include <memory>

class TaskQueue;

class Task {
public:
virtual void consume(TaskQueue& queue) = 0;
};

using ITask = std::unique_ptr<Task>;

class TaskQueue {
public:
std::queue<ITask> tasks;
void process() {
while(!tasks.empty()) {
tasks.front()->consume(*this);
}
}
};

class Ephemeral : public Task {
public:
explicit Ephemeral(std::string data) : data(std::move(data)) {};
std::string data;
void consume(TaskQueue& queue) override {
std::cout << "Might fail but I am leaving anyway! " << data << std::endl; // Do some work that might fail
queue.tasks.pop(); // SELF-ERASURE
};
};

class Guaranteed : public Task {
public:
explicit Guaranteed(std::string data, unsigned int repetitions) : data(std::move(data)), repetitions(repetitions) {};
std::string data;
unsigned int repetitions; // For demonstration purpose
unsigned int attempt_count;
void consume(TaskQueue& queue) override {
std::cout << "I am not leaving unless I succeed! " << data << std::endl;
++attempt_count;
bool success = attempt(); // Might (artificially) fail
if(success) { queue.tasks.pop(); } // SELF-ERASURE on success
};
bool attempt() { return attempt_count == repetitions;}; // Do some work that might fail
};

int main() {
ITask task1 = std::make_unique<Ephemeral>("Fire and forget!");
ITask task2 = std::make_unique<Guaranteed>("Success on first try!", 1);
ITask task3 = std::make_unique<Guaranteed>("Give me some time!", 3);
ITask task4 = std::make_unique<Ephemeral>("I did it!");
ITask task5 = std::make_unique<Guaranteed>("Some troubles ahead!", 2);
TaskQueue task_queue;
task_queue.tasks.push(std::move(task1));
task_queue.tasks.push(std::move(task2));
task_queue.tasks.push(std::move(task3));
task_queue.tasks.push(std::move(task4));
task_queue.tasks.push(std::move(task5));
task_queue.process();
}

结果:

Might fail but I am leaving anyway! Fire and forget!
I am not leaving unless I succeed! Success on first try!
I am not leaving unless I succeed! Give me some time!
I am not leaving unless I succeed! Give me some time!
I am not leaving unless I succeed! Give me some time!
Might fail but I am leaving anyway! I did it!
I am not leaving unless I succeed! Some troubles ahead!
I am not leaving unless I succeed! Some troubles ahead!

您认为这段代码是否合适,还是有更好的方法?这对我来说似乎过于复杂,但我很难找到一种不使用 self 删除/ self 删除并且不在 process() 函数中再次测试的合适方法。

最后,我认为我们可以这样重新表述这个问题:有一个容器可以让元素自行离开吗?

像这样:

GatheringQueue<Participant> gathering_queue{element1, element2, element3};
Participant element = gathering_queue.get_front();
// Some stuff
element.leave(); // We leave the queue for some reason

在我看来,这有点类似于邮局排队,排队的一些人可以等着看他们的包裹是否真的离开了,另一些人只会把包裹留在这儿而不关心会发生什么, 他们立即离开队伍。

为了完整起见,这里是我能在堆栈溢出中找到的所有内容,或多或少与主题相关:

Object delete itself from container

Remove self from the container in the lambda

Self erasing workers c++

最佳答案

为什么不在每个任务上都有一个 ephemeral 标志,然后在 TaskQueue 中弹出:

#include <iostream>
#include <queue>
#include <memory>

class TaskQueue;

class Task {
public:
Task(bool ephemeral): ephemeral(ephemeral) {}
virtual ~Task() {}
virtual bool process() = 0;

bool isEphemeral() const { return ephemeral; }
private:
const bool ephemeral;
};

using ITask = std::unique_ptr<Task>;

class TaskQueue {
public:
std::queue<ITask> tasks;
void process() {
while(!tasks.empty()) {
auto& task = tasks.front();
bool success = false;
try
{
success = task->process();
}
catch (std::exception& ex)
{
std::cout << "task failed: " << ex.what();
}
if (success || task->isEphemeral())
{
tasks.pop();
}
}
}
};

class Ephemeral : public Task {
public:
explicit Ephemeral(std::string data) : Task(true), data(std::move(data)) {};
std::string data;
bool process() override {
std::cout << "Might fail but I am leaving anyway! " << data << std::endl; // Do some work that might fail
return true;
};
};

class Guaranteed : public Task {
public:
explicit Guaranteed(std::string data, unsigned int repetitions) : Task(false), data(std::move(data)), repetitions(repetitions) {};
std::string data;
unsigned int repetitions; // For demonstration purpose
unsigned int attempt_count;
bool process() override {
std::cout << "I am not leaving unless I succeed! " << data << std::endl;
++attempt_count;
bool success = attempt(); // Might (artificially) fail
return success;
};
bool attempt() { return attempt_count == repetitions;}; // Do some work that might fail
};

int main() {
ITask task1 = std::make_unique<Ephemeral>("Fire and forget!");
ITask task2 = std::make_unique<Guaranteed>("Success on first try!", 1);
ITask task3 = std::make_unique<Guaranteed>("Give me some time!", 3);
ITask task4 = std::make_unique<Ephemeral>("I did it!");
ITask task5 = std::make_unique<Guaranteed>("Some troubles ahead!", 2);
TaskQueue task_queue;
task_queue.tasks.push(std::move(task1));
task_queue.tasks.push(std::move(task2));
task_queue.tasks.push(std::move(task3));
task_queue.tasks.push(std::move(task4));
task_queue.tasks.push(std::move(task5));
task_queue.process();
}

任务现在是自包含的,不需要知道它们的容器,更重要的是它消除了对象 self 销毁的未定义行为。

如果您愿意,您可以删除 ephemeral 标志并只将 isEphemeral 设为虚拟。

我还在 Task 中添加了一个 virtual 析构函数,否则派生类将不会被正确删除。我已将异常处理添加到任务处理中以防万一,但如果您的任务不抛出异常,则可以将其删除。

关于c++ - 作业/任务消耗队列,自删除项目的有效案例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57682071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com