thrift多线程服务端

接上一篇 thrift一个例子 

作为服务端,应该能够同时接收多个客户端传来的数据,所以服务端应该实现多线程机制。

按以下3个步骤改写服务端(Serv_server.skeleton.cpp)即可实现多线程。

(1)采用线程池的main函数的代码如下:

int main(int argc, char **argv) {
 // thread pool
 shared_ptr<ServHandler> handler(new ServHandler());
 shared_ptr<TProcessor> processor(new ServProcessor(handler));
 shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
  shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
  shared_ptr<TServerTransport> serverTransport(new TServerSocket(9090));

// 指定15个线程

  shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(15);
  shared_ptr<PosixThreadFactory> threadFactory
  = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());

  threadManager->threadFactory(threadFactory);
  threadManager->start();
  printf("start.../n");
 
  TThreadPoolServer server(processor,
                           serverTransport,
                           transportFactory,
                           protocolFactory,
                           threadManager);

  server.serve();

  printf("end/n");
  return 0;
}

注意代码中的红色关键字,要将他们修改成你自己的service中定义的名字。

(2)头文件:

#include <concurrency/ThreadManager.h>
#include <concurrency/PosixThreadFactory.h>

#include <server/TThreadPoolServer.h>
#include <server/TThreadedServer.h>

能加的都加上吧,以免出现类似如下错误:

error: ‘ThreadManager’ was not declared in this scope

(3)命名空间:using namespace ::apache::thrift::concurrency;

否则出现错误:error: ‘PosixThreadFactory’ was not declared in this scope

concurrency是和#include中的文件目录是对应的

 

每一个客户端连接时,服务端都将启动一个线程为其服务,数据传输结束后,服务端回收这个线程。

 

你可能感兴趣的:(apache,thread,多线程,server,service,concurrency)