接上一篇 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中的文件目錄是對應的
每一個客戶端連接時,服務端都將啓動一個線程爲其服務,數據傳輸結束後,服務端回收這個線程。