handle.h

#ifndef ASYNCIO_HANDLE_H
#define ASYNCIO_HANDLE_H

#include <cstdint>
#include <source_location>
#include <fmt/core.h>

namespace ASYNCIO_NS {
// for cancelled
using HandleId = uint64_t;

/*
句柄类,回调类
*/
struct Handle { // type erase for EventLoop
    enum State: uint8_t {
        UNSCHEDULED,
        SUSPEND,
        SCHEDULED,
    };

    Handle() noexcept: handle_id_(handle_id_generation_++) {}
    virtual void run() = 0;
    void set_state(State state) { state_ = state; }
    HandleId get_handle_id() { return handle_id_; }
    virtual ~Handle() = default;
private:
    HandleId handle_id_;
    static HandleId handle_id_generation_;
protected:
    State state_ {Handle::UNSCHEDULED};
};

// handle maybe destroyed, using the increasing id to track the lifetime of handle.
// don't directly using a raw pointer to track coroutine lifetime,
// because a destroyed coroutine may has the same address as a new ready coroutine has created.
/*
通过id来追踪句柄
*/
struct HandleInfo {
    HandleId id { };
    Handle* handle { };
};

/*
协程句柄类
实现在event_loop.cpp
*/
struct CoroHandle: Handle {
    // 帧
    std::string frame_name() const {
        const auto& frame_info = get_frame_info();
        return fmt::format("{} at {}:{}", frame_info.function_name(),
                           frame_info.file_name(), frame_info.line());
    }

    virtual void dump_backtrace(size_t depth = 0) const {};
    
    void schedule();
    
    void cancel();
private:
    virtual const std::source_location& get_frame_info() const;
};

}

#endif // ASYNCIO_HANDLE_H

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值