一、thrift 共有5中工作模式,分成阻塞和非阻塞:
阻塞:TSimpleServer、TThreadPoolServer
非阻塞:TNonblockingServer、THsHaServer、TThreadedSelectorServer
這里的阻塞是指,如果同時有多個新鏈接到來,但一次只能處理一個新連接,即當前的鏈接會阻塞后續鏈接的處理。
非阻塞則是,當有許多新連接到來時,會同時獲得這些鏈接的列表,一次性處理一批鏈接。
二者的區別在加上線程池的時候就顯現出來了,阻塞模式一次只能往池子里扔一個鏈接,而非阻塞一次可以扔一堆鏈接。
但池子本身大小是優先的,所以一般高並發場景並不適合用線程池模式。
具體的工作模式參考:https://blog.csdn.net/houjixin/article/details/42779915
二、線程池模式代碼:
作為服務端,應該能夠同時接收多個客戶端傳來的數據,所以服務端應該實現多線程機制。
按以下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中的文件目錄是對應的
每一個客戶端連接時,服務端都將啟動一個線程為其服務,數據傳輸結束后,服務端回收這個線程。
https://blog.csdn.net/hbuxiaoshe/article/details/6560285