我正在尝试在 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
),但会阻塞构造函数RunServer()
因为grpcServer->Wait()
称呼。尝试使用线程,我收到编译器错误:call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type
不打电话grpcServer->Wait()
导致服务器立即关闭RunServer()
退出,尽管变量grpcServer
只要类实例正在运行,它就仍然在范围内。
我该如何正确开始grpcServer
并将其放在后台?