grpc c++ example有以下评论。
// Spawn a new CallData instance to serve new clients while we process
// the one for this CallData.
我对这句话有点困惑,因为它似乎表明新的 CallData 实例可以同时为不同的客户端提供服务。 (这是一个事件循环吗?)
但是我没有看到示例中创建任何新线程。我是否正确地假设没有创建新线程并且 CallData 可能作用的任何共享变量不需要互斥体?或者是否需要互斥锁?
例如,如果示例中的代码更改为以下内容,我是否需要互斥锁?
...
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_);
// Do I need a mutex here?
// mutex.lock()
service->do_something_to_variable();
// mutex.unlock()
std::string prefix("Hello ");
reply_.set_message(prefix + request_.name());
最佳答案
我会尽力回答您的每个问题。
I'm a bit confused by the sentence as it seems to suggest the new CallData >instance can potentially serve a different client simultaneously. (Is it an event >loop?)
这里的事件循环是HandleRpcs()中cq_->Next()的循环。创建一个新的 CallData 开始为另一个客户端提供服务的过程(您可以在其构造函数中看到它调用 service_->RequestSayHello,这使得系统能够处理另一个传入的 RPC)。一旦调用此函数,有关新传入 RPC 的事件就会添加到完成队列中。如果前一个 rpc 尚未完成,则该 rpc 的事件将添加到完成队列中。这意味着我们使用新的 CallData 来处理新的 rpc,同时使用旧的 CallData 来处理以前的 rpc。
Am I correct to assume that no new threads are created and any shared variables that CallData might act on, does not need a mutex? Or is a mutex necessary?
是的,所以本例中没有创建新线程。唯一起作用的线程是运行 HandleRpcs() 的线程。因此,当我在上面的答案中谈论“同时”时,这是指任何时候都有多个正在进行的 RPC(每个 RPC 都有自己的 CallData),但处理实际上并不是并发的,因为示例应用程序中只有一个线程。现在,如果图中有多个线程,则使用互斥锁来保护 CallData 的状态可能是一个好主意(取决于是否可以共享对状态的访问)。
For example if the code in the example was changed to the below, would I need a mutex?
如果您编写的内容是对代码的唯一更改,则不,您不需要互斥体(而且我不确定您尝试在 service_ 上调用什么方法)。
关于c++ - grpc c++ 异步服务器示例,处理状态下是否需要互斥锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58724528/