schedule_task.h

#ifndef ASYNCIO_SCHEDULE_TASK_H
#define ASYNCIO_SCHEDULE_TASK_H

#include <asyncio/noncopyable.h>
#include <asyncio/concept/future.h>
namespace ASYNCIO_NS {

// 封装Task(一构造就加入调度)
template<concepts::Future Task>
struct ScheduledTask: private NonCopyable {
    template<concepts::Future Fut>
    explicit ScheduledTask(Fut&& fut): task_(std::forward<Fut>(fut)) {
        if (task_.valid() && ! task_.done()) {
            task_.handle_.promise().schedule();
        }
    }

    void cancel() { task_.destroy(); }

    decltype(auto) operator co_await() const & noexcept {
        return task_.operator co_await();
    }

    auto operator co_await() const && noexcept {
        return task_.operator co_await();
    }

    decltype(auto) get_result() & {
        return task_.get_result();
    }

    decltype(auto) get_result() && {
        return std::move(task_).get_result();
    }

    bool valid() const { return task_.valid(); }

    bool done() const { return task_.done(); }

private:
    Task task_;
};

template<concepts::Future Fut>
ScheduledTask(Fut&&) -> ScheduledTask<Fut>;

template<concepts::Future Fut>
[[nodiscard("discard(detached) a task will not schedule to run")]]
ScheduledTask<Fut> schedule_task(Fut&& fut) {
    return ScheduledTask { std::forward<Fut>(fut) };
}

}
#endif // ASYNCIO_SCHEDULE_TASK_H

posted @ 2024-07-12 16:58  DavidJIAN  阅读(37)  评论(0)    收藏  举报