gpt4 book ai didi

c++ - 后台线程中的grpc服务器c++

转载 作者:行者123 更新时间:2023-12-05 07:09:20 24 4
gpt4 key购买 nike

我正在尝试在 MFC 应用程序的线程中运行 grpc 服务器。

我有(直接来自 GRPC 示例的 grpc 部分):

MyAppDlg.h:

#include <thread>
#include <grpcpp\grpcpp.h>

class MyAppDlg : public CDialog
{
public:
MyAppDlg( CString aFileName, CWnd *pParent = NULL );
virtual ~MyAppDlg();

std::unique_ptr<grpc::Server> grpcServer;

std::thread grpcThread;

void RunServer();

MyAppDlg.cpp:

class GreeterServiceImpl final : public Greeter::Service {
Status SayHello(ServerContext* context, const HelloRequest* request,
HelloReply* reply) override {
std::string prefix("Hello ");
reply->set_message(prefix + request->name());
return Status::OK;
}
};

void MyAppDlg::RunServer() {
std::string server_address("0.0.0.0:50051");
GreeterServiceImpl service;
grpc::EnableDefaultHealthCheckService(true);
grpc::reflection::InitProtoReflectionServerBuilderPlugin();
ServerBuilder builder;
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
builder.RegisterService(&service);
std::unique_ptr<Server> grpcServer(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;

// Wait for the server to shutdown. Note that some other thread must be
// responsible for shutting down the server for this call to ever return.
grpcServer->Wait(); <-- Leaving this out causes the server to close immediately again.
}

MyAppDlg::MyAppDlg( CString aFileName, CWnd* pParent /* =NULL */ )
{
... stuff ...
// RunServer(); <-- using this works but blocks the thread
grpcThread(RunServer); <-- does not work

}

MyAppDlg::~MyAppDlg()
{
grpcServer->Shutdown();
grpcThread.join();
}

没有线程,它运行良好(客户端可以连接并调用 SayHello),但由于 grpcServer-> 阻塞了 RunServer() 的构造函数等待 () 调用。在线程中尝试,我得到一个编译器错误:call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type

不调用 grpcServer->Wait() 导致服务器在 RunServer() 退出后立即关闭,尽管变量 grpcServer 仍然存在只要类实例正在运行就在范围内。

如何正确启动 grpcServer 并将其置于后台?

最佳答案

我认为问题出在 MyAppDlg::RunServer() 中的这一行:

std::unique_ptr<Server> grpcServer(builder.BuildAndStart());

您正在定义一个名为 grpcServer 的局部变量,而不是分配给同名的类数据成员,因此它会在 RunServer() 返回。我认为应该是:

grpcServer.reset(builder.BuildAndStart());

关于c++ - 后台线程中的grpc服务器c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61635906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com