brpc源码:闭包类ClosureGuard

源码路径

src\brpc\closure_guard.h

主要方法有:

  • 构造+析构
  • reset
  • release
  • empty
  • swap

这个类主要用来保证程序对象释放前执行某个方法

构造+析构

    ClosureGuard() : _done(NULL) {}

    // Constructed with a closure which will be Run() inside dtor.
    explicit ClosureGuard(google::protobuf::Closure* done) : _done(done) {}
    
    // Run internal closure if it's not NULL.
    ~ClosureGuard() {
        if (_done) {
            _done->Run();
        }
    }

析构保证了构造时传的done方法一定会被执行,可以参考brpc示例:

brpc/incubator-brpc/example/asynchronous_echo_c++/server.cpp

在服务的实现中,对客户端传来的done方法用闭包类进行了封装:

    virtual void Echo(google::protobuf::RpcController* cntl_base,
                      const example::EchoRequest* request,
                      example::EchoResponse* response,
                      google::protobuf::Closure* done) {
        // This object helps you to call done->Run() in RAII style. If you need
        // to process the request asynchronously, pass done_guard.release().
        brpc::ClosureGuard done_guard(done);
……

这样在请求返回前就一定会执行done方法

 

reset

    void reset(google::protobuf::Closure* done) {
        if (_done) {
            _done->Run();
        }
        _done = done;
    }

这个方法是对闭包封装的方法进行重置,但是重置前一定会执行该方法。

 

release

    google::protobuf::Closure* release() {
        google::protobuf::Closure* const prev_done = _done;
        _done = NULL;
        return prev_done;
    }

这个方法用于对内部方法done置空,返回之前的done

另外的empty 用于判断done是否为空,swap 用于和另外一个闭包的done方法进行交换

 

用法

类的用法之一是在brpc用于异步调用时,客户端将回调函数通过参数传给server,由server给回调函数构建一个闭包对象,保证回调在返回前会执行,可参考:brpc源码:server类

 

closure_guard.h

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值