Commit 15fb7938 authored by Pavel Vainerman's avatar Pavel Vainerman

Глобальный переход (по возможности)

shared_ptr --> unique_ptr
parent 1b8e0075
......@@ -24,6 +24,7 @@
#include <iomanip>
#include <cmath>
#include "unisetstd.h"
#include "ORepHelpers.h"
#include "DBServer_MySQL.h"
#include "Configuration.h"
......@@ -35,14 +36,9 @@ using namespace uniset;
using namespace std;
// --------------------------------------------------------------------------
DBServer_MySQL::DBServer_MySQL(ObjectId id, const std::string& prefix ):
DBServer(id, prefix),
PingTime(300000),
ReconnectTime(180000),
connect_ok(false),
activate(true),
qbufSize(200),
lastRemove(false)
{
DBServer(id, prefix)
{
if( getId() == DefaultObjectId )
{
ostringstream msg;
......@@ -50,7 +46,7 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id, const std::string& prefix ):
throw Exception(msg.str());
}
db = make_shared<MySQLInterface>();
db = unisetstd::make_unique<MySQLInterface>();
mqbuf.setName(myname + "_qbufMutex");
}
......@@ -279,9 +275,9 @@ void DBServer_MySQL::initDBServer()
tblMap[uniset::Message::SensorInfo] = "main_history";
tblMap[uniset::Message::Confirm] = "main_history";
PingTime = conf->getIntProp(node, "pingTime");
ReconnectTime = conf->getIntProp(node, "reconnectTime");
qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), 200);
PingTime = conf->getPIntProp(node, "pingTime",PingTime);
ReconnectTime = conf->getPIntProp(node, "reconnectTime",ReconnectTime);
qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), qbufSize);
if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 )
lastRemove = true;
......
......@@ -161,7 +161,7 @@ namespace uniset
typedef std::unordered_map<int, std::string> DBTableMap;
virtual void initDBServer() override;
virtual void initDB( std::shared_ptr<MySQLInterface>& db ) {};
virtual void initDB( const std::unique_ptr<MySQLInterface>& db ) {};
virtual void initDBTableMap(DBTableMap& tblMap) {};
virtual void timerInfo( const uniset::TimerMessage* tm ) override;
......@@ -185,18 +185,18 @@ namespace uniset
};
std::shared_ptr<MySQLInterface> db;
int PingTime;
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
std::unique_ptr<MySQLInterface> db;
int PingTime = { 15000 };
int ReconnectTime = { 30000 };
bool connect_ok = { false }; /*! признак наличия соеднинения с сервером БД */
bool activate;
bool activate = { false };
typedef std::queue<std::string> QueryBuffer;
QueryBuffer qbuf;
unsigned int qbufSize; // размер буфера сообщений.
bool lastRemove;
size_t qbufSize = { 200 }; // размер буфера сообщений.
bool lastRemove = { false };
void flushBuffer();
uniset::uniset_rwmutex mqbuf;
......
......@@ -19,6 +19,7 @@
#include <iomanip>
#include <cmath>
#include "unisetstd.h"
#include "ORepHelpers.h"
#include "DBServer_PostgreSQL.h"
#include "Configuration.h"
......@@ -30,15 +31,9 @@ using namespace uniset;
using namespace std;
// --------------------------------------------------------------------------
DBServer_PostgreSQL::DBServer_PostgreSQL(ObjectId id, const std::string& prefix ):
DBServer(id, prefix),
PingTime(300000),
ReconnectTime(180000),
connect_ok(false),
activate(true),
qbufSize(200),
lastRemove(false)
DBServer(id, prefix)
{
db = make_shared<PostgreSQLInterface>();
db = unisetstd::make_unique<PostgreSQLInterface>();
if( getId() == DefaultObjectId )
{
......@@ -49,15 +44,9 @@ DBServer_PostgreSQL::DBServer_PostgreSQL(ObjectId id, const std::string& prefix
}
DBServer_PostgreSQL::DBServer_PostgreSQL():
DBServer(uniset_conf()->getDBServer()),
db(make_shared<PostgreSQLInterface>()),
PingTime(300000),
ReconnectTime(180000),
connect_ok(false),
activate(true),
qbufSize(200),
lastRemove(false)
DBServer(uniset_conf()->getDBServer())
{
db = unisetstd::make_unique<PostgreSQLInterface>();
// init();
if( getId() == DefaultObjectId )
......@@ -333,10 +322,10 @@ void DBServer_PostgreSQL::initDBServer()
tblMap[uniset::Message::SensorInfo] = "main_history";
tblMap[uniset::Message::Confirm] = "main_history";
PingTime = conf->getArgPInt("--" + prefix + "-pingTime", it.getProp("pingTime"), 15000);
ReconnectTime = conf->getArgPInt("--" + prefix + "-reconnectTime", it.getProp("reconnectTime"), 30000);
PingTime = conf->getArgPInt("--" + prefix + "-pingTime", it.getProp("pingTime"), PingTime);
ReconnectTime = conf->getArgPInt("--" + prefix + "-reconnectTime", it.getProp("reconnectTime"), ReconnectTime);
qbufSize = conf->getArgPInt("--" + prefix + "-buffer-size", it.getProp("bufferSize"), 200);
qbufSize = conf->getArgPInt("--" + prefix + "-buffer-size", it.getProp("bufferSize"), qbufSize);
if( findArgParam("--" + prefix + "-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 )
lastRemove = true;
......
......@@ -78,7 +78,7 @@ namespace uniset
typedef std::unordered_map<int, std::string> DBTableMap;
virtual void initDBServer() override;
virtual void initDB( std::shared_ptr<PostgreSQLInterface>& db ) {};
virtual void initDB( std::unique_ptr<PostgreSQLInterface>& db ) {};
virtual void initDBTableMap(DBTableMap& tblMap) {};
virtual void timerInfo( const uniset::TimerMessage* tm ) override;
......@@ -103,24 +103,24 @@ namespace uniset
lastNumberOfTimer
};
std::shared_ptr<PostgreSQLInterface> db;
std::unique_ptr<PostgreSQLInterface> db;
int PingTime = { 15000 };
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
int ReconnectTime = { 30000 };
bool activate;
bool connect_ok = { false }; /*! признак наличия соеднинения с сервером БД */
bool activate = { false };
typedef std::queue<std::string> QueryBuffer;
QueryBuffer qbuf;
size_t qbufSize; // размер буфера сообщений.
size_t qbufSize = { 200 }; // размер буфера сообщений.
bool lastRemove = { false };
void flushBuffer();
std::mutex mqbuf;
// writeBuffer
const std::list<std::string> tblcols = { "date", "time", "time_usec", "sensor_id", "value", "node" };
const std::vector<std::string> tblcols = { "date", "time", "time_usec", "sensor_id", "value", "node" };
typedef std::vector<PostgreSQLInterface::Record> InsertBuffer;
InsertBuffer ibuf;
......
......@@ -86,7 +86,7 @@ bool PostgreSQLInterface::close()
return true;
}
// -----------------------------------------------------------------------------------------
bool PostgreSQLInterface::copy( const std::string& tblname, const std::list<std::string>& cols,
bool PostgreSQLInterface::copy( const std::string& tblname, const std::vector<std::string>& cols,
const PostgreSQLInterface::Data& data )
{
if( !db )
......
......@@ -57,7 +57,7 @@ namespace uniset
typedef std::vector<Record> Data;
// fast insert: Use COPY..from SDTIN..
bool copy( const std::string& tblname, const std::list<std::string>& cols, const Data& data );
bool copy( const std::string& tblname, const std::vector<std::string>& cols, const Data& data );
virtual const std::string error() override;
......
......@@ -64,7 +64,7 @@ int main(int argc, char** argv)
if( ver == 3 )
{
std::list<std::string> cols = { "date", "time", "time_usec", "sensor_id", "value", "node" };
std::vector<std::string> cols = { "date", "time", "time_usec", "sensor_id", "value", "node" };
PostgreSQLInterface::Data data;
for( size_t i = 0; i < num; i++ )
......
......@@ -24,6 +24,7 @@
#include <iomanip>
#include <cmath>
#include "unisetstd.h"
#include "ORepHelpers.h"
#include "DBServer_SQLite.h"
#include "Configuration.h"
......@@ -35,13 +36,7 @@ using namespace uniset;
using namespace std;
// --------------------------------------------------------------------------
DBServer_SQLite::DBServer_SQLite( ObjectId id, const std::string& prefix ):
DBServer(id, prefix),
PingTime(300000),
ReconnectTime(180000),
connect_ok(false),
activate(true),
qbufSize(200),
lastRemove(false)
DBServer(id, prefix)
{
if( getId() == DefaultObjectId )
{
......@@ -50,7 +45,7 @@ DBServer_SQLite::DBServer_SQLite( ObjectId id, const std::string& prefix ):
throw Exception(msg.str());
}
db = make_shared<SQLiteInterface>();
db = unisetstd::make_unique<SQLiteInterface>();
}
DBServer_SQLite::DBServer_SQLite( const std::string& prefix ):
......@@ -259,9 +254,9 @@ void DBServer_SQLite::initDBServer()
tblMap[uniset::Message::SensorInfo] = "main_history";
tblMap[uniset::Message::Confirm] = "main_history";
PingTime = conf->getIntProp(node, "pingTime");
ReconnectTime = conf->getIntProp(node, "reconnectTime");
qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), 200);
PingTime = conf->getPIntProp(node, "pingTime",PingTime);
ReconnectTime = conf->getPIntProp(node, "reconnectTime",ReconnectTime);
qbufSize = conf->getArgPInt("--dbserver-buffer-size", it.getProp("bufferSize"), qbufSize);
if( findArgParam("--dbserver-buffer-last-remove", conf->getArgc(), conf->getArgv()) != -1 )
lastRemove = true;
......
......@@ -161,8 +161,8 @@ namespace uniset
typedef std::unordered_map<int, std::string> DBTableMap;
virtual void initDBServer() override;
virtual void initDB( std::shared_ptr<SQLiteInterface>& db ) {};
virtual void initDBTableMap(DBTableMap& tblMap) {};
virtual void initDB( const std::unique_ptr<SQLiteInterface>& db ) {};
virtual void initDBTableMap( DBTableMap& tblMap ) {};
virtual void timerInfo( const uniset::TimerMessage* tm ) override;
virtual void sysCommand( const uniset::SystemMessage* sm ) override;
......@@ -184,19 +184,18 @@ namespace uniset
lastNumberOfTimer
};
std::unique_ptr<SQLiteInterface> db;
int PingTime = { 300000 };
int ReconnectTime = { 180000 };
std::shared_ptr<SQLiteInterface> db;
int PingTime;
int ReconnectTime;
bool connect_ok; /*! признак наличия соеднинения с сервером БД */
bool activate;
bool connect_ok = { false }; /*! признак наличия соеднинения с сервером БД */
bool activate = { false };
typedef std::queue<std::string> QueryBuffer;
QueryBuffer qbuf;
unsigned int qbufSize; // размер буфера сообщений.
bool lastRemove;
size_t qbufSize = { 200 }; // размер буфера сообщений.
bool lastRemove = { false };
void flushBuffer();
uniset::uniset_rwmutex mqbuf;
......
......@@ -19,6 +19,7 @@
#include <sstream>
#include <Exceptions.h>
#include <extensions/Extensions.h>
#include "unisetstd.h"
#include "MBTCPMaster.h"
#include "modbus/MBLogSugar.h"
// -----------------------------------------------------------------------------
......@@ -69,7 +70,7 @@ MBTCPMaster::MBTCPMaster(uniset::ObjectId objId, uniset::ObjectId shmId,
else
ic->addReadItem( sigc::mem_fun(this, &MBTCPMaster::readItem) );
pollThread = make_shared<ThreadCreator<MBTCPMaster>>(this, &MBTCPMaster::poll_thread);
pollThread = unisetstd::make_unique<ThreadCreator<MBTCPMaster>>(this, &MBTCPMaster::poll_thread);
pollThread->setFinalAction(this, &MBTCPMaster::final_thread);
if( mblog->is_info() )
......
......@@ -283,7 +283,7 @@ namespace uniset
// т.к. TCP может "зависнуть" на подключении к недоступному узлу
// делаем опрос в отдельном потоке
std::shared_ptr<ThreadCreator<MBTCPMaster>> pollThread; /*!< поток опроса */
std::unique_ptr<ThreadCreator<MBTCPMaster>> pollThread; /*!< поток опроса */
};
// --------------------------------------------------------------------------
} // end of namespace uniset
......
......@@ -18,8 +18,9 @@
#include <limits>
#include <iomanip>
#include <sstream>
#include <Exceptions.h>
#include <extensions/Extensions.h>
#include "unisetstd.h"
#include "Exceptions.h"
#include "extensions/Extensions.h"
#include "MBTCPMultiMaster.h"
#include "modbus/MBLogSugar.h"
// -----------------------------------------------------------------------------
......@@ -186,9 +187,9 @@ MBTCPMultiMaster::MBTCPMultiMaster( uniset::ObjectId objId, uniset::ObjectId shm
else
ic->addReadItem( sigc::mem_fun(this, &MBTCPMultiMaster::readItem) );
pollThread = make_shared<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::poll_thread);
pollThread =unisetstd::make_unique<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::poll_thread);
pollThread->setFinalAction(this, &MBTCPMultiMaster::final_thread);
checkThread = make_shared<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::check_thread);
checkThread = unisetstd::make_unique<ThreadCreator<MBTCPMultiMaster>>(this, &MBTCPMultiMaster::check_thread);
checkThread->setFinalAction(this, &MBTCPMultiMaster::final_thread);
// Т.к. при "многоканальном" доступе к slave, смена канала должна происходит сразу после
......
......@@ -380,8 +380,8 @@ namespace uniset
// т.к. TCP может "зависнуть" на подключении к недоступному узлу
// делаем опрос в отдельном потоке
std::shared_ptr< ThreadCreator<MBTCPMultiMaster> > pollThread; /*!< поток опроса */
std::shared_ptr< ThreadCreator<MBTCPMultiMaster> > checkThread; /*!< поток проверки связи по другим каналам */
std::unique_ptr< ThreadCreator<MBTCPMultiMaster> > pollThread; /*!< поток опроса */
std::unique_ptr< ThreadCreator<MBTCPMultiMaster> > checkThread; /*!< поток проверки связи по другим каналам */
};
// --------------------------------------------------------------------------
} // end of namespace uniset
......
......@@ -17,6 +17,7 @@
#include <cmath>
#include <sstream>
#include <Poco/Net/NetException.h>
#include "unisetstd.h"
#include "Exceptions.h"
#include "Extensions.h"
#include "MBSlave.h"
......@@ -180,7 +181,7 @@ namespace uniset
// rs->setLog(mblog);
mbslot = std::static_pointer_cast<ModbusServerSlot>(rs);
thr = make_shared< ThreadCreator<MBSlave> >(this, &MBSlave::execute_rtu);
thr = unisetstd::make_unique< ThreadCreator<MBSlave> >(this, &MBSlave::execute_rtu);
thr->setFinalAction(this, &MBSlave::finalThread);
mbinfo << myname << "(init): type=RTU dev=" << dev << " speed=" << speed << endl;
......
......@@ -555,7 +555,7 @@ namespace uniset
MBSlave();
timeout_t initPause = { 3000 };
uniset::uniset_rwmutex mutex_start;
std::shared_ptr< ThreadCreator<MBSlave> > thr;
std::unique_ptr< ThreadCreator<MBSlave> > thr;
std::mutex mutexStartNotify;
std::condition_variable startNotifyEvent;
......
......@@ -332,9 +332,9 @@ void RRDServer::askSensors( UniversalIO::UIOCommand cmd )
// прежде чем заказывать датчики, надо убедиться что SM доступна
waitSM(smReadyTimeout);
for( auto& it : rrdlist )
for( const auto& it : rrdlist )
{
for( auto& s : it.dsmap )
for( const auto& s : it.dsmap )
{
try
{
......@@ -354,7 +354,7 @@ void RRDServer::sysCommand( const uniset::SystemMessage* sm )
if( sm->command == SystemMessage::StartUp || sm->command == SystemMessage::WatchDog )
{
for( auto && it : rrdlist )
for( const auto& it : rrdlist )
{
try
{
......@@ -370,7 +370,7 @@ void RRDServer::sysCommand( const uniset::SystemMessage* sm )
// -----------------------------------------------------------------------------
void RRDServer::sensorInfo( const uniset::SensorMessage* sm )
{
for( auto& it : rrdlist )
for( const auto& it : rrdlist )
{
auto s = it.dsmap.find(sm->id);
......@@ -383,7 +383,7 @@ void RRDServer::sensorInfo( const uniset::SensorMessage* sm )
// -----------------------------------------------------------------------------
void RRDServer::timerInfo( const uniset::TimerMessage* tm )
{
for( auto& it : rrdlist )
for( const auto& it : rrdlist )
{
if( it.tid == tm->id )
{
......
......@@ -133,11 +133,11 @@ namespace uniset
// Т.к. RRD требует чтобы данные записывались именно в том порядке в котором они были добавлены
// при инициализации и при этом, нам нужен быстрый доступ в обработчике sensorInfo.
// То создаём list<> для последовательного прохода по элементам в нужном порядке
// То создаём vector<> для последовательного прохода по элементам в нужном порядке
// и unordered_map<> для быстрого доступа к элементам в sensorInfo
// При этом используем shared_ptr чтобы элементы указывали на один и тот же DSInfo
typedef std::unordered_map<uniset::ObjectId, std::shared_ptr<DSInfo>> DSMap;
typedef std::list<std::shared_ptr<DSInfo>> DSList;
typedef std::vector<std::shared_ptr<DSInfo>> DSList;
struct RRDInfo
{
......@@ -150,7 +150,7 @@ namespace uniset
RRDInfo( const std::string& fname, long tmID, long sec, const DSList& lst );
};
typedef std::list<RRDInfo> RRDList;
typedef std::vector<RRDInfo> RRDList;
RRDList rrdlist;
......
......@@ -17,6 +17,7 @@
#include <sstream>
#include <iomanip>
#include <Poco/Net/NetException.h>
#include "unisetstd.h"
#include "Exceptions.h"
#include "Extensions.h"
#include "UNetReceiver.h"
......@@ -76,7 +77,7 @@ UNetReceiver::UNetReceiver(const std::string& s_host, int _port, const std::shar
auto conf = uniset_conf();
conf->initLogStream(unetlog, myname);
upThread = make_shared< ThreadCreator<UNetReceiver> >(this, &UNetReceiver::updateThread);
upThread = unisetstd::make_unique< ThreadCreator<UNetReceiver> >(this, &UNetReceiver::updateThread);
if( !createConnection(nocheckConnection /* <-- это флаг throwEx */) )
evCheckConnection.set<UNetReceiver, &UNetReceiver::checkConnectionEvent>(this);
......@@ -206,7 +207,7 @@ bool UNetReceiver::createConnection( bool throwEx )
try
{
udp = make_shared<UDPReceiveU>(addr, port);
udp = unisetstd::make_unique<UDPReceiveU>(addr, port);
udp->setBlocking(false); // делаем неблокирующее чтение (нужно для libev)
evReceive.set<UNetReceiver, &UNetReceiver::callback>(this);
......
......@@ -242,7 +242,7 @@ namespace uniset
timeout_t recvpause = { 10 }; /*!< пауза меджду приёмами пакетов, [мсек] */
timeout_t updatepause = { 100 }; /*!< переодичность обновления данных в SM, [мсек] */
std::shared_ptr<UDPReceiveU> udp;
std::unique_ptr<UDPReceiveU> udp;
std::string addr;
int port = { 0 };
Poco::Net::SocketAddress saddr;
......@@ -263,7 +263,7 @@ namespace uniset
size_t statRecvPerSec = { 0 }; /*!< количество принимаемых пакетов в секунду */
size_t statUpPerSec = { 0 }; /*!< количество обработанных пакетов в секунду */
std::shared_ptr< ThreadCreator<UNetReceiver> > upThread; // update thread
std::unique_ptr< ThreadCreator<UNetReceiver> > upThread; // update thread
// делаем loop общим.. одним на всех!
static CommonEventLoop loop;
......
......@@ -17,6 +17,7 @@
#include <sstream>
#include <iomanip>
#include <Poco/Net/NetException.h>
#include "unisetstd.h"
#include "Exceptions.h"
#include "Extensions.h"
#include "UNetSender.h"
......@@ -70,7 +71,7 @@ namespace uniset
ptCheckConnection.setTiming(10000); // default 10 сек
createConnection(nocheckConnection);
s_thr = make_shared< ThreadCreator<UNetSender> >(this, &UNetSender::send);
s_thr = unisetstd::make_unique< ThreadCreator<UNetSender> >(this, &UNetSender::send);
mypacks[0].resize(1);
packs_anum[0] = 0;
......@@ -115,7 +116,7 @@ namespace uniset
try
{
//udp = make_shared<UDPSocketU>(addr, port);
udp = make_shared<UDPSocketU>();
udp = unisetstd::make_unique<UDPSocketU>();
udp->setBroadcast(true);
udp->setSendTimeout( UniSetTimer::millisecToPoco(writeTimeout) );
// udp->setNoDelay(true);
......
......@@ -186,7 +186,7 @@ namespace uniset
private:
UNetSender();
std::shared_ptr<UDPSocketU> udp = { nullptr };
std::unique_ptr<UDPSocketU> udp;
std::string addr;
int port = { 0 };
std::string s_host = { "" };
......@@ -214,7 +214,7 @@ namespace uniset
size_t maxAData = { UniSetUDP::MaxACount };
size_t maxDData = { UniSetUDP::MaxDCount };
std::shared_ptr< ThreadCreator<UNetSender> > s_thr; // send thread
std::unique_ptr< ThreadCreator<UNetSender> > s_thr; // send thread
size_t ncycle = { 0 }; /*!< номер цикла посылки */
......
......@@ -99,7 +99,7 @@ namespace uniset
ev::dynamic_loop loop;
ev::async evterm;
std::shared_ptr<std::thread> thr;
std::unique_ptr<std::thread> thr;
std::mutex thr_mutex;
std::mutex term_mutex;
......
......@@ -61,7 +61,7 @@ namespace uniset
std::timed_mutex run_mutex;
ev::async evterm;
std::shared_ptr<std::thread> thr;
std::unique_ptr<std::thread> thr;
std::mutex looprunOK_mutex;
std::condition_variable looprunOK_event;
......
......@@ -200,7 +200,7 @@ namespace uniset
return transport(*this);
}
int command;
int command = { 0 };
long data[2];
};
std::ostream& operator<<( std::ostream& os, const SystemMessage::Command& c );
......@@ -255,17 +255,17 @@ namespace uniset
ObjectId sensor_id; /* ID датчика (события) */
double sensor_value; /* значение датчика (события) */
struct timespec sensor_time; /* время срабатывания датчика(события), который квитируем */
struct timespec confirm_time; /* * время прошедшее до момента квитирования */
struct timespec sensor_time = { 0, 0 }; /* время срабатывания датчика(события), который квитируем */
struct timespec confirm_time = { 0, 0 }; /* * время прошедшее до момента квитирования */
bool broadcast;
bool broadcast = { false };
/*!
признак, что сообщение является пересланным.
(т.е. в БД второй раз сохранять не надо, пересылать
второй раз тоже не надо).
*/
bool forward;
bool forward = { false };
protected:
ConfirmMessage() noexcept;
......
......@@ -234,14 +234,14 @@ namespace uniset
std::atomic_bool active;
bool threadcreate;
std::shared_ptr<UniSetTimer> tmr;
std::unique_ptr<UniSetTimer> tmr;
uniset::ObjectId myid;
CORBA::Object_var oref;
/*! замок для блокирования совместного доступа к oRef */
mutable uniset::uniset_rwmutex refmutex;
std::shared_ptr< ThreadCreator<UniSetObject> > thr;
std::unique_ptr< ThreadCreator<UniSetObject> > thr;
/*! очереди сообщений в зависимости от приоритета */
MQMutex mqueueLow;
......
......@@ -186,7 +186,17 @@ namespace uniset
protected:
std::string filename;
std::shared_ptr<xmlDoc> doc = { nullptr };
struct UniXMLDocDeleter
{
void operator()(xmlDoc* doc) const noexcept
{
if( doc )
xmlFreeDoc(doc);
}
};
std::unique_ptr<xmlDoc,UniXMLDocDeleter> doc;
};
// -------------------------------------------------------------------------
} // end of uniset namespace
......
/*
* Copyright (c) 2015 Pavel Vainerman.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 2.1.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// --------------------------------------------------------------------------
/*! \file
* \author Pavel Vainerman
* \brief Всякие доп. функции расширяющие std::
*/
// --------------------------------------------------------------------------
#ifndef UniSetCPP_H_
#define UniSetCPP_H_
// --------------------------------------------------------------------------
#include <memory>
#include <utility>
namespace unisetstd {
template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}
// --------------------------------------------------------------------------
} // end of namespace unisetcpp
// --------------------------------------------------------------------------
#endif
......@@ -29,6 +29,7 @@
#include <chrono>
#include <Poco/Process.h>
#include "unisetstd.h"
#include "Exceptions.h"
#include "ORepHelpers.h"
#include "ObjectRepository.h"
......@@ -42,7 +43,7 @@ using namespace std;
namespace uniset
{
#define CREATE_TIMER make_shared<PassiveCondTimer>();
#define CREATE_TIMER unisetstd::make_unique<PassiveCondTimer>();
// new PassiveSysTimer();
// ------------------------------------------------------------------------------------------
......@@ -758,7 +759,7 @@ namespace uniset
if( myid != uniset::DefaultObjectId && threadcreate )
{
thr = std::make_shared< ThreadCreator<UniSetObject> >(this, &UniSetObject::work);
thr = unisetstd::make_unique< ThreadCreator<UniSetObject> >(this, &UniSetObject::work);
//thr->setCancel(ost::Thread::cancelDeferred);
std::unique_lock<std::mutex> locker(m_working);
......
#include <iostream>
#include <chrono>
#include <algorithm>
#include "unisetstd.h"
#include "CommonEventLoop.h"
// -------------------------------------------------------------------------
using namespace std;
......@@ -42,7 +43,7 @@ namespace uniset
if( thr )
return true;
thr = make_shared<std::thread>( [&] { CommonEventLoop::defaultLoop(); } );
thr = unisetstd::make_unique<std::thread>( [&] { CommonEventLoop::defaultLoop(); } );
std::unique_lock<std::mutex> lock2(looprunOK_mutex);
looprunOK_event.wait_for(lock2, std::chrono::milliseconds(waitTimeout_msec), [&]()
......
#include <iostream>
#include "unisetstd.h"
#include "EventLoopServer.h"
// -------------------------------------------------------------------------
using namespace std;
......@@ -57,7 +58,7 @@ namespace uniset
}
if( !thr )
thr = make_shared<std::thread>( [&] { defaultLoop(); } );
thr = unisetstd::make_unique<std::thread>( [&] { defaultLoop(); } );
bool ret = waitDefaultLoopRunning(timeout_msec);
......
......@@ -64,19 +64,6 @@ string UniXML::getFileName() const noexcept
return filename;
}
// -----------------------------------------------------------------------------
struct UniXMLDocDeleter
{
void operator()(xmlDoc* doc) const noexcept
{
try
{
if( doc )
xmlFreeDoc(doc);
}
catch(...) {}
}
};
// -----------------------------------------------------------------------------
void UniXML::newDoc(const string& root_node, const string& xml_ver)
{
assert(doc == nullptr); // предыдущий doc не удален из памяти
......@@ -87,7 +74,7 @@ void UniXML::newDoc(const string& root_node, const string& xml_ver)
if( d == NULL )
throw NameNotFound("UniXML(open): не смогли создать doc=" + root_node);
doc = std::shared_ptr<xmlDoc>(d, UniXMLDocDeleter());
doc = std::unique_ptr<xmlDoc,UniXMLDocDeleter>(d);
// xmlEncodeEntitiesReentrant(doc, (const xmlChar*)ExternalEncoding.c_str());
xmlNode* rootnode = xmlNewDocNode(d, NULL, (const xmlChar*)root_node.c_str(), NULL);
......@@ -131,7 +118,7 @@ void UniXML::open( const string& _filename )
if( d == NULL )
throw NameNotFound("UniXML(open): NotFound file=" + _filename);
doc = std::shared_ptr<xmlDoc>(d, UniXMLDocDeleter());
doc = std::unique_ptr<xmlDoc,UniXMLDocDeleter>(d);
// Support for XInclude (see eterbug #6304)
// main tag must to have follow property: xmlns:xi="http://www.w3.org/2001/XInclude"
......
......@@ -347,6 +347,7 @@ include/UHelpers.h
include/UHttpRequestHandler.h
include/UHttpServer.h
include/ujson.h
include/unisetstd.h
lib/Makefile.am
python/examples/test.xml
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment