[英]grpc c++ async completion queue events
我試圖了解 grpc c++ 異步 model 流程。 這篇文章( 鏈接)已經解釋了我的許多疑惑。 這是grpc_asycn_server的代碼。 為了了解 CompletionQueue 何時收到請求,我添加了一些打印語句,如下所示:
首先在 HandleRpcs() function 中。
void HandleRpcs() {
// Spawn a new CallData instance to serve new clients.
new CallData(&service_, cq_.get());
void* tag; // uniquely identifies a request.
bool ok;
int i = 0;
while (true) {
std::cout << i << std::endl; ///////////////////////////////
// Block waiting to read the next event from the completion queue. The
// event is uniquely identified by its tag, which in this case is the
// memory address of a CallData instance.
// The return value of Next should always be checked. This return value
// tells us whether there is any kind of event or cq_ is shutting down.
GPR_ASSERT(cq_->Next(&tag, &ok));
GPR_ASSERT(ok);
static_cast<CallData*>(tag)->Proceed();
i++;
}
}
在proceed() function中:
void Proceed() {
if (status_ == CREATE) {
// Make this instance progress to the PROCESS state.
status_ = PROCESS;
// As part of the initial CREATE state, we *request* that the system
// start processing SayHello requests. In this request, "this" acts are
// the tag uniquely identifying the request (so that different CallData
// instances can serve different requests concurrently), in this case
// the memory address of this CallData instance.
std::cout<<"RequestSayHello called"<<std::endl; ////////////////////////////
service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
this);
} else if (status_ == PROCESS) {
// Spawn a new CallData instance to serve new clients while we process
// the one for this CallData. The instance will deallocate itself as
// part of its FINISH state.
new CallData(service_, cq_);
// The actual processing.
std::string prefix("Hello ");
reply_.set_message(prefix + request_.name());
// And we are done! Let the gRPC runtime know we've finished, using the
// memory address of this instance as the uniquely identifying tag for
// the event.
status_ = FINISH;
responder_.Finish(reply_, Status::OK, this);
} else {
std::cout<<"deallocated"<<std::endl; ////////////////////////////
GPR_ASSERT(status_ == FINISH);
// Once in the FINISH state, deallocate ourselves (CallData).
delete this;
}
}
一旦我運行服務器和一個客戶端( 客戶端),服務器就會打印以下內容:
RequestSayHello called
i = 0
RequestSayHello called
i = 1
deallocated
i = 2
由於創建了新的CallData
實例,調用的第二個RequestSayHello called
是有意義的。 我的問題是如何proceed()
function 第二次執行並deallocated
被打印?
完成隊列 ( cq_
) 結構處理多種類型的事件,包括請求和響應事件。 對proceed()
的第一次調用進入PROCESS
機器的處理階段,用於CallData
object。
在此階段:
1、新建CallData
object; 如您所述,這會將請求事件插入cq_
2. responder_
_被調用,回復為object; 這會將響應事件插入cq_
在收到來自cq_
的響應事件后,在第一個CallData
object 上再次調用proceed()
,它現在位於FINISH
state 中,因此執行清理並打印deallocated
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.