我正在使用Apache Thrift框架,我正在编写一个具有C ++服务器和python客户端的应用程序。应用程序有一个很大的资源对象,在生命中使用。我的应用程序需要有一个重载方法。它应该删除所有资源,并从磁盘加载新实例。我编写了清理方法,并在加载方法之前调用它。如果我使用TSimpleServer(单线程),这是有用的。但是,当我开始使用ThreadedServer或TNonBlocking服务器(多线程)时,cleannig方法不起作用,我可以看到,它正在调用,但它不会清理。服务器刚刚开始使用两倍的内存量。我试图在清洁方法中使用互斥锁,但这没有帮助。 对我来说,似乎问题在于多线程,远程方法在子线程中启动,因此它们无法释放在主线程中分配的资源。
template<typename T>
void deleteProcessors(T &processor) {
for (typename T::iterator iter = processor.begin(); iter != processor.end(); ++iter) {
delete iter->second;
}
processor.clear();
}
class taggerHandler : virtual public taggerIf {
public:
taggerHandler() {
this->loadResources();
}
void tagText(std::string& _return, const std::string& text, const std::string& language) {
//useful function
}
void reload(std::string& _return, const std::string& parmeters) {
this->clearResources();
this->loadResources();
}
private:
void loadResources() {
//here config reading, option declaring etc..
//maco just object from freeling library, could allocate >100MB
string language = "en";
this->macoProcs[language] = shared_ptr<maco>(new maco());
}
void clearResources(){
macoProcs.clear();
//this way was before shared_ptr
//deleteProcessors(macoProcs);
}
map<string, shared_ptr<maco> > macoProcs;
//this way was before shared_ptr
//map<string, maco*> macoProcs;
};
节俭初始化:
int main(int argc, char **argv) {
shared_ptr<taggerHandler> handler(new taggerHandler());
shared_ptr<TProcessor> processor(new taggerProcessor(handler));
shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(15);
shared_ptr<PosixThreadFactory> threadFactory = shared_ptr<PosixThreadFactory>(new PosixThreadFactory());
threadManager->threadFactory(threadFactory);
threadManager->start();
//TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);
TNonblockingServer server(processor, protocolFactory, port, threadManager);
server.serve();
return 0;
}`