How to check if caller still exist in task callback

允我心安 提交于 2021-02-11 18:10:12

问题


A very common scenario for a thread's callback is to inform the caller that it has finished his job. Here's the minimal example:

class task
{
public:
    void operator()(std::function<void()>&& callback)
    {
        std::thread t
        {
            [c = std::move(callback)]{
                std::this_thread::sleep_for(std::chrono::milliseconds{100});
                c();
            }
        };
        t.detach();
    }
};

class processor
{
public:
    void new_task()
    {
        auto& t = tasks.emplace_back();
        t([this]{ if (true/*this object still alives*/) finish_callback(); });
    }
    
private:
    void finish_callback()
    {
        // ...
    }
    
private:
    std::vector<task> tasks;
};

In such scenario, we have to support the case when the child task overlives the parent/caller. Is there any common design pattern that allows us to do this?

Theoretically, we may use shared_ptr + enable_shared_from_this + weak_ptr trio in such case, but this forces us to always store the parent object on the heap under shared_ptr. I would rather like to not have such a limitation.

来源:https://stackoverflow.com/questions/63102457/how-to-check-if-caller-still-exist-in-task-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!