源码路径
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类