Commit 5029e89a authored by Pavel Vainerman's avatar Pavel Vainerman

Оптимизация: перешёл на deque вместо list, там где во основном, проход по списку…

Оптимизация: перешёл на deque вместо list, там где во основном, проход по списку или обавление в начало или конец очереди (буфер).
parent b4b70147
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
#define SQLiteInterface_H_ #define SQLiteInterface_H_
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
#include <string> #include <string>
#include <list> #include <deque>
#include <vector> #include <vector>
#include <iostream> #include <iostream>
#include <sqlite3.h> #include <sqlite3.h>
...@@ -45,10 +45,10 @@ class SQLiteResult; ...@@ -45,10 +45,10 @@ class SQLiteResult;
cerr << "db connect error: " << db.error() << endl; cerr << "db connect error: " << db.error() << endl;
return 1; return 1;
} }
stringstream q; stringstream q;
q << "SELECT * from main_history"; q << "SELECT * from main_history";
SQLiteResult r = db.query(q.str()); SQLiteResult r = db.query(q.str());
if( !r ) if( !r )
{ {
...@@ -86,7 +86,7 @@ class SQLiteResult; ...@@ -86,7 +86,7 @@ class SQLiteResult;
class SQLiteInterface class SQLiteInterface
{ {
public: public:
SQLiteInterface(); SQLiteInterface();
~SQLiteInterface(); ~SQLiteInterface();
...@@ -94,7 +94,7 @@ class SQLiteInterface ...@@ -94,7 +94,7 @@ class SQLiteInterface
bool close(); bool close();
bool isConnection(); bool isConnection();
bool ping(); // проверка доступности БД bool ping(); // проверка доступности БД
void setOperationTimeout( timeout_t msec ); void setOperationTimeout( timeout_t msec );
inline timeout_t getOperationTimeout(){ return opTimeout; } inline timeout_t getOperationTimeout(){ return opTimeout; }
...@@ -115,15 +115,15 @@ class SQLiteInterface ...@@ -115,15 +115,15 @@ class SQLiteInterface
static bool checkResult( int rc ); static bool checkResult( int rc );
private: private:
sqlite3* db; sqlite3* db;
// sqlite3_stmt* curStmt; // sqlite3_stmt* curStmt;
std::string lastQ; std::string lastQ;
std::string lastE; std::string lastE;
bool queryok; // успешность текущего запроса bool queryok; // успешность текущего запроса
bool connected; bool connected;
timeout_t opTimeout; timeout_t opTimeout;
timeout_t opCheckPause; timeout_t opCheckPause;
}; };
...@@ -136,10 +136,10 @@ class SQLiteResult ...@@ -136,10 +136,10 @@ class SQLiteResult
~SQLiteResult(); ~SQLiteResult();
typedef std::vector<std::string> COL; typedef std::vector<std::string> COL;
typedef std::list<COL> ROW; typedef std::deque<COL> ROW;
typedef ROW::iterator iterator; typedef ROW::iterator iterator;
inline iterator begin(){ return res.begin(); } inline iterator begin(){ return res.begin(); }
inline iterator end(){ return res.end(); } inline iterator end(){ return res.end(); }
......
...@@ -258,7 +258,7 @@ void IOControl::execute() ...@@ -258,7 +258,7 @@ void IOControl::execute()
waitSM(); // необходимо дождаться, чтобы нормально инициализировать итераторы waitSM(); // необходимо дождаться, чтобы нормально инициализировать итераторы
PassiveTimer pt(UniSetTimer::WaitUpTime); PassiveTimer pt(UniSetTimer::WaitUpTime);
if( shm->isLocalwork() ) if( shm->isLocalwork() )
{ {
maxItem = 0; maxItem = 0;
...@@ -276,11 +276,11 @@ void IOControl::execute() ...@@ -276,11 +276,11 @@ void IOControl::execute()
readconf_ok = true; // т.к. waitSM() уже был... readconf_ok = true; // т.к. waitSM() уже был...
} }
maxHalf = maxItem / 2; maxHalf = maxItem / 2;
dinfo << myname << "(init): iomap size = " << iomap.size() << endl; dinfo << myname << "(init): iomap size = " << iomap.size() << endl;
cerr << myname << "(iomap size): " << iomap.size() << endl; //cerr << myname << "(iomap size): " << iomap.size() << endl;
// чтение параметров по входам-выходам // чтение параметров по входам-выходам
initIOCard(); initIOCard();
...@@ -387,10 +387,10 @@ void IOControl::execute() ...@@ -387,10 +387,10 @@ void IOControl::execute()
if( term ) if( term )
break; break;
msleep( polltime ); msleep( polltime );
} }
term = false; term = false;
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
...@@ -398,7 +398,7 @@ void IOControl::iopoll() ...@@ -398,7 +398,7 @@ void IOControl::iopoll()
{ {
if( testmode == tmOffPoll ) if( testmode == tmOffPoll )
return; return;
// Опрос приоритетной очереди // Опрос приоритетной очереди
for( PIOMap::iterator it=pmap.begin(); it!=pmap.end(); ++it ) for( PIOMap::iterator it=pmap.begin(); it!=pmap.end(); ++it )
{ {
...@@ -419,7 +419,7 @@ void IOControl::iopoll() ...@@ -419,7 +419,7 @@ void IOControl::iopoll()
IOBase::processingThreshold((IOBase*)&(*it),shm,force); IOBase::processingThreshold((IOBase*)&(*it),shm,force);
ioread( (IOInfo*)&(*it) ); ioread( (IOInfo*)&(*it) );
// на середине // на середине
// опять опросим приоритетные // опять опросим приоритетные
if( !prior && i>maxHalf ) if( !prior && i>maxHalf )
...@@ -432,11 +432,11 @@ void IOControl::iopoll() ...@@ -432,11 +432,11 @@ void IOControl::iopoll()
IOBase::processingThreshold((IOBase*)&(iomap[it->index]),shm,force); IOBase::processingThreshold((IOBase*)&(iomap[it->index]),shm,force);
} }
} }
prior = true; prior = true;
} }
} }
// Опрос приоритетной очереди // Опрос приоритетной очереди
for( PIOMap::iterator it=pmap.begin(); it!=pmap.end(); ++it ) for( PIOMap::iterator it=pmap.begin(); it!=pmap.end(); ++it )
{ {
...@@ -543,7 +543,7 @@ void IOControl::ioread( IOInfo* it ) ...@@ -543,7 +543,7 @@ void IOControl::ioread( IOInfo* it )
card->setDigitalChannel(it->subdev,it->channel,0); card->setDigitalChannel(it->subdev,it->channel,0);
} }
break; break;
case lmpON: case lmpON:
{ {
if( force_out && (prev_val == lmpBLINK if( force_out && (prev_val == lmpBLINK
...@@ -760,7 +760,7 @@ bool IOControl::initIOItem( UniXML_iterator& it ) ...@@ -760,7 +760,7 @@ bool IOControl::initIOItem( UniXML_iterator& it )
// после инициализации делается resize // после инициализации делается resize
// под реальное количество // под реальное количество
if( maxItem >= iomap.size() ) if( maxItem >= iomap.size() )
iomap.resize(maxItem+10); iomap.resize(maxItem+90);
int prior = it.getIntProp("iopriority"); int prior = it.getIntProp("iopriority");
if( prior > 0 ) if( prior > 0 )
...@@ -771,7 +771,7 @@ bool IOControl::initIOItem( UniXML_iterator& it ) ...@@ -771,7 +771,7 @@ bool IOControl::initIOItem( UniXML_iterator& it )
<< it.getProp("name") << it.getProp("name")
<< " priority=" << prior << endl; << " priority=" << prior << endl;
} }
iomap[maxItem++] = inf; iomap[maxItem++] = inf;
return true; return true;
} }
...@@ -972,9 +972,9 @@ void IOControl::check_testmode() ...@@ -972,9 +972,9 @@ void IOControl::check_testmode()
if( prev_testmode == testmode ) if( prev_testmode == testmode )
return; return;
prev_testmode = testmode; prev_testmode = testmode;
// если режим "выключено всё" // если режим "выключено всё"
// то гасим все выходы // то гасим все выходы
if( testmode == tmOffPoll ) if( testmode == tmOffPoll )
...@@ -1039,10 +1039,10 @@ void IOControl::check_testlamp() ...@@ -1039,10 +1039,10 @@ void IOControl::check_testlamp()
{ {
if( force_out ) if( force_out )
isTestLamp = shm->localGetValue( itTestLamp, testLamp_S ); isTestLamp = shm->localGetValue( itTestLamp, testLamp_S );
if( !trTestLamp.change(isTestLamp) ) if( !trTestLamp.change(isTestLamp) )
return; // если состояние не менялось, то продолжаем работу... return; // если состояние не менялось, то продолжаем работу...
if( isTestLamp ) if( isTestLamp )
blink_state = true; // первый такт всегда зажигаем... blink_state = true; // первый такт всегда зажигаем...
...@@ -1054,7 +1054,7 @@ void IOControl::check_testlamp() ...@@ -1054,7 +1054,7 @@ void IOControl::check_testlamp()
{ {
if( !it->lamp || it->no_testlamp ) if( !it->lamp || it->no_testlamp )
continue; continue;
if( it->stype == UniversalIO::AO ) if( it->stype == UniversalIO::AO )
{ {
if( isTestLamp ) if( isTestLamp )
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
#define IOControl_H_ #define IOControl_H_
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include <vector> #include <vector>
#include <list> #include <deque>
#include <string> #include <string>
#include "UniXML.h" #include "UniXML.h"
#include "PassiveTimer.h" #include "PassiveTimer.h"
...@@ -66,19 +66,19 @@ ...@@ -66,19 +66,19 @@
<br>\b --io-ready-timeout - Время ожидания готовности SM к работе, мсек. (-1 - ждать 'вечно') <br>\b --io-ready-timeout - Время ожидания готовности SM к работе, мсек. (-1 - ждать 'вечно')
<br>\b --io-force - Сохранять значения в SM, независимо от, того менялось ли значение <br>\b --io-force - Сохранять значения в SM, независимо от, того менялось ли значение
<br>\b --io-force-out - Обновлять выходы принудительно (не по заказу) <br>\b --io-force-out - Обновлять выходы принудительно (не по заказу)
<br>\b --io-skip-init-output - Не инициализировать 'выходы' при старте <br>\b --io-skip-init-output - Не инициализировать 'выходы' при старте
<br>\b --io-sm-ready-test-sid - Использовать указанный датчик, для проверки готовности SharedMemory <br>\b --io-sm-ready-test-sid - Использовать указанный датчик, для проверки готовности SharedMemory
\par Возможные настройки по каждому входу/выходу \par Возможные настройки по каждому входу/выходу
<br>\b nofilter - не использовать фильтр <br>\b nofilter - не использовать фильтр
<br>\b ioignore - игнорировать данный датчик (позволяет временно отключить вход/выход) <br>\b ioignore - игнорировать данный датчик (позволяет временно отключить вход/выход)
<br>\b ioinvert - инвертированная логика (для DI,DO) <br>\b ioinvert - инвертированная логика (для DI,DO)
<br>\b default - значение по умолчанию (при запуске) <br>\b default - значение по умолчанию (при запуске)
<br>\b noprecision - игнорировать поле precision (т.е. процесс в/в не будет его использовать, <br>\b noprecision - игнорировать поле precision (т.е. процесс в/в не будет его использовать,
но будет его присылать в SensorMessage) но будет его присылать в SensorMessage)
<br>\b breaklim - пороговое значение для определения обырва датчика (используется для AI). <br>\b breaklim - пороговое значение для определения обырва датчика (используется для AI).
Если значение ниже этого порога, то выставляется признак обрыва датчика. Если значение ниже этого порога, то выставляется признак обрыва датчика.
<br>\b jardelay - защита от дребезга. Задержка на дребезг, мсек. <br>\b jardelay - защита от дребезга. Задержка на дребезг, мсек.
...@@ -129,7 +129,7 @@ ...@@ -129,7 +129,7 @@
<br>UniSetTypes::lmpBLINK - мигание с частотой 1 <br>UniSetTypes::lmpBLINK - мигание с частотой 1
<br>UniSetTypes::lmpBLINK2 - мигание с частотой 2 <br>UniSetTypes::lmpBLINK2 - мигание с частотой 2
<br>UniSetTypes::lmpBLINK3 - мигание с частотой 3 <br>UniSetTypes::lmpBLINK3 - мигание с частотой 3
<br>\b no_iotestlamp - игнорировать данную лампочку при тесте ламп. <br>\b no_iotestlamp - игнорировать данную лампочку при тесте ламп.
<br>\b range - диапазон измерения аналогового входа (см. libcomedi) <br>\b range - диапазон измерения аналогового входа (см. libcomedi)
<br>\b aref - тип подключения (см. libcomedi) <br>\b aref - тип подключения (см. libcomedi)
...@@ -249,7 +249,7 @@ class IOControl: ...@@ -249,7 +249,7 @@ class IOControl:
bool no_testlamp; /*!< флаг исключения из 'проверки ламп' */ bool no_testlamp; /*!< флаг исключения из 'проверки ламп' */
bool enable_testmode; /*!< флаг для режима тестирования tmConfigEnable */ bool enable_testmode; /*!< флаг для режима тестирования tmConfigEnable */
bool disable_testmode; /*!< флаг для режима тестирования tmConfigDisable */ bool disable_testmode; /*!< флаг для режима тестирования tmConfigDisable */
friend std::ostream& operator<<(std::ostream& os, IOInfo& inf ); friend std::ostream& operator<<(std::ostream& os, IOInfo& inf );
}; };
...@@ -257,11 +257,11 @@ class IOControl: ...@@ -257,11 +257,11 @@ class IOControl:
{ {
IOPriority(int p, int i): IOPriority(int p, int i):
priority(p),index(i){} priority(p),index(i){}
int priority; int priority;
int index; int index;
}; };
enum TestModeID enum TestModeID
{ {
tmNone = 0, /*!< тестовый режим отключён */ tmNone = 0, /*!< тестовый режим отключён */
...@@ -315,8 +315,8 @@ class IOControl: ...@@ -315,8 +315,8 @@ class IOControl:
typedef std::vector<IOInfo> IOMap; typedef std::vector<IOInfo> IOMap;
IOMap iomap; /*!< список входов/выходов */ IOMap iomap; /*!< список входов/выходов */
typedef std::list<IOPriority> PIOMap; typedef std::deque<IOPriority> PIOMap;
PIOMap pmap; /*!< список приоритетных входов/выходов */ PIOMap pmap; /*!< список приоритетных входов/выходов */
unsigned int maxItem; /*!< количество элементов (используется на момент инициализации) */ unsigned int maxItem; /*!< количество элементов (используется на момент инициализации) */
...@@ -327,7 +327,7 @@ class IOControl: ...@@ -327,7 +327,7 @@ class IOControl:
std::string s_field; std::string s_field;
std::string s_fvalue; std::string s_fvalue;
SMInterface* shm; SMInterface* shm;
UInterface ui; UInterface ui;
UniSetTypes::ObjectId myid; UniSetTypes::ObjectId myid;
std::string prefix; std::string prefix;
...@@ -342,7 +342,7 @@ class IOControl: ...@@ -342,7 +342,7 @@ class IOControl:
BlinkList lstBlink; BlinkList lstBlink;
PassiveTimer ptBlink; PassiveTimer ptBlink;
bool blink_state; bool blink_state;
// мигание с двойной частотой // мигание с двойной частотой
BlinkList lstBlink2; BlinkList lstBlink2;
PassiveTimer ptBlink2; PassiveTimer ptBlink2;
...@@ -352,7 +352,7 @@ class IOControl: ...@@ -352,7 +352,7 @@ class IOControl:
BlinkList lstBlink3; BlinkList lstBlink3;
PassiveTimer ptBlink3; PassiveTimer ptBlink3;
bool blink3_state; bool blink3_state;
UniSetTypes::ObjectId testLamp_S; UniSetTypes::ObjectId testLamp_S;
Trigger trTestLamp; Trigger trTestLamp;
bool isTestLamp; bool isTestLamp;
......
...@@ -555,7 +555,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode ) ...@@ -555,7 +555,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode )
for( ; it.getCurrent(); it.goNext() ) for( ; it.getCurrent(); it.goNext() )
{ {
HistoryInfo hi; HistoryInfo hi;
hi.id = it.getIntProp("id"); hi.id = it.getIntProp("id");
hi.size = it.getIntProp("size"); hi.size = it.getIntProp("size");
if( hi.size <= 0 ) if( hi.size <= 0 )
continue; continue;
...@@ -589,7 +589,6 @@ void SharedMemory::buildHistoryList( xmlNode* cnode ) ...@@ -589,7 +589,6 @@ void SharedMemory::buildHistoryList( xmlNode* cnode )
<< " fuse_invert=" << hi.fuse_invert << " fuse_invert=" << hi.fuse_invert
<< endl; << endl;
// WARNING: no check duplicates... // WARNING: no check duplicates...
hist.push_back(hi); hist.push_back(hi);
} }
...@@ -609,6 +608,7 @@ void SharedMemory::checkHistoryFilter( UniXML_iterator& xit ) ...@@ -609,6 +608,7 @@ void SharedMemory::checkHistoryFilter( UniXML_iterator& xit )
if( !xit.getProp("id").empty() ) if( !xit.getProp("id").empty() )
{ {
ai.id = xit.getIntProp("id"); ai.id = xit.getIntProp("id");
ai.init( it->size, xit.getIntProp("default") );
it->hlst.push_back(ai); it->hlst.push_back(ai);
continue; continue;
} }
...@@ -620,6 +620,7 @@ void SharedMemory::checkHistoryFilter( UniXML_iterator& xit ) ...@@ -620,6 +620,7 @@ void SharedMemory::checkHistoryFilter( UniXML_iterator& xit )
continue; continue;
} }
ai.init( it->size, xit.getIntProp("default") );
it->hlst.push_back(ai); it->hlst.push_back(ai);
} }
} }
......
...@@ -280,6 +280,12 @@ class SharedMemory: ...@@ -280,6 +280,12 @@ class SharedMemory:
{ {
HistoryItem():id(UniSetTypes::DefaultObjectId){} HistoryItem():id(UniSetTypes::DefaultObjectId){}
inline void init( unsigned int size, long val )
{
if( size > 0 )
buf.assign(size,val);
}
UniSetTypes::ObjectId id; UniSetTypes::ObjectId id;
HBuffer buf; HBuffer buf;
...@@ -287,9 +293,11 @@ class SharedMemory: ...@@ -287,9 +293,11 @@ class SharedMemory:
void add( long val, size_t size ) void add( long val, size_t size )
{ {
// т.е. буфер у нас уже заданного размера
// то просто удаляем очередную точку в начале
// и добавляем в конце
buf.pop_front();
buf.push_back(val); buf.push_back(val);
if( buf.size() >= size )
buf.pop_front();
} }
}; };
...@@ -312,10 +320,10 @@ class SharedMemory: ...@@ -312,10 +320,10 @@ class SharedMemory:
} }
long id; // ID long id; // ID
HistoryList hlst; // history list HistoryList hlst; // history list
int size; int size;
std::string filter; // filter field std::string filter; // filter field
UniSetTypes::ObjectId fuse_id; // fuse sesnsor UniSetTypes::ObjectId fuse_id; // fuse sesnsor
bool fuse_invert; bool fuse_invert;
bool fuse_use_val; bool fuse_use_val;
long fuse_val; long fuse_val;
......
...@@ -153,7 +153,7 @@ sender2(0) ...@@ -153,7 +153,7 @@ sender2(0)
} }
bool resp_invert = n_it.getIntProp("unet_respond_invert"); bool resp_invert = n_it.getIntProp("unet_respond_invert");
string s_resp_id(n_it.getProp("unet_respond1_id")); string s_resp_id(n_it.getProp("unet_respond1_id"));
UniSetTypes::ObjectId resp_id = UniSetTypes::DefaultObjectId; UniSetTypes::ObjectId resp_id = UniSetTypes::DefaultObjectId;
if( !s_resp_id.empty() ) if( !s_resp_id.empty() )
...@@ -236,7 +236,7 @@ sender2(0) ...@@ -236,7 +236,7 @@ sender2(0)
dcrit << myname << "(init): " << err.str() << endl; dcrit << myname << "(init): " << err.str() << endl;
throw SystemError(err.str()); throw SystemError(err.str());
} }
} }
dinfo << myname << "(init): (node='" << n << "') add receiver " dinfo << myname << "(init): (node='" << n << "') add receiver "
<< h2 << ":" << p2 << endl; << h2 << ":" << p2 << endl;
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
#include <ostream> #include <ostream>
#include <string> #include <string>
#include <queue> #include <queue>
#include <deque>
#include <cc++/socket.h> #include <cc++/socket.h>
#include "UniSetObject_LT.h" #include "UniSetObject_LT.h"
#include "Trigger.h" #include "Trigger.h"
...@@ -16,7 +17,7 @@ ...@@ -16,7 +17,7 @@
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
/*! /*!
\page pageUNetExchangeUDP Сетевой обмен на основе UDP (UNetUDP) \page pageUNetExchangeUDP Сетевой обмен на основе UDP (UNetUDP)
- \ref pgUNetUDP_Common - \ref pgUNetUDP_Common
- \ref pgUNetUDP_Conf - \ref pgUNetUDP_Conf
- \ref pgUNetUDP_Reserv - \ref pgUNetUDP_Reserv
...@@ -81,7 +82,7 @@ class UNetExchange: ...@@ -81,7 +82,7 @@ class UNetExchange:
public: public:
UNetExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, SharedMemory* ic=0, const std::string& prefix="unet" ); UNetExchange( UniSetTypes::ObjectId objId, UniSetTypes::ObjectId shmID, SharedMemory* ic=0, const std::string& prefix="unet" );
virtual ~UNetExchange(); virtual ~UNetExchange();
/*! глобальная функция для инициализации объекта */ /*! глобальная функция для инициализации объекта */
static UNetExchange* init_unetexchange( int argc, const char* argv[], static UNetExchange* init_unetexchange( int argc, const char* argv[],
UniSetTypes::ObjectId shmID, SharedMemory* ic=0, const std::string& prefix="unet" ); UniSetTypes::ObjectId shmID, SharedMemory* ic=0, const std::string& prefix="unet" );
...@@ -114,7 +115,6 @@ class UNetExchange: ...@@ -114,7 +115,6 @@ class UNetExchange:
void initIterators(); void initIterators();
void startReceivers(); void startReceivers();
enum Timer enum Timer
{ {
...@@ -151,7 +151,7 @@ class UNetExchange: ...@@ -151,7 +151,7 @@ class UNetExchange:
respondInvert(false), respondInvert(false),
sidLostPackets(UniSetTypes::DefaultObjectId) sidLostPackets(UniSetTypes::DefaultObjectId)
{} {}
UNetReceiver* r1; /*!< приём по первому каналу */ UNetReceiver* r1; /*!< приём по первому каналу */
UNetReceiver* r2; /*!< приём по второму каналу */ UNetReceiver* r2; /*!< приём по второму каналу */
...@@ -179,8 +179,8 @@ class UNetExchange: ...@@ -179,8 +179,8 @@ class UNetExchange:
UniSetTypes::ObjectId sidLostPackets; UniSetTypes::ObjectId sidLostPackets;
IOController::IOStateList::iterator itLostPackets; IOController::IOStateList::iterator itLostPackets;
}; };
typedef std::list<ReceiverInfo> ReceiverList; typedef std::deque<ReceiverInfo> ReceiverList;
ReceiverList recvlist; ReceiverList recvlist;
bool no_sender; /*!< флаг отключения посылки сообщений (создания потока для посылки)*/ bool no_sender; /*!< флаг отключения посылки сообщений (создания потока для посылки)*/
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
#include <cmath> #include <cmath>
#include <string> #include <string>
#include <vector> #include <vector>
#include <deque>
#include <ostream> #include <ostream>
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
/*! /*!
...@@ -232,7 +233,7 @@ class Calibration ...@@ -232,7 +233,7 @@ class Calibration
} }
}; };
typedef std::vector<CacheInfo> ValueCache; typedef std::deque<CacheInfo> ValueCache;
ValueCache cache; ValueCache cache;
unsigned long numCacheResort; // количество обращений, при которых происходит перестроение (сортировка) кэша.. unsigned long numCacheResort; // количество обращений, при которых происходит перестроение (сортировка) кэша..
unsigned long numCallToCache; // текущий счётчик обращений к кэшу unsigned long numCallToCache; // текущий счётчик обращений к кэшу
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
#ifndef DigitalFilter_H_ #ifndef DigitalFilter_H_
#define DigitalFilter_H_ #define DigitalFilter_H_
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
#include <list> #include <deque>
#include <vector> #include <vector>
#include <ostream> #include <ostream>
#include "PassiveTimer.h" #include "PassiveTimer.h"
...@@ -16,7 +16,7 @@ class DigitalFilter ...@@ -16,7 +16,7 @@ class DigitalFilter
int iir_thr=10000, double iir_coeff_prev=0.5, int iir_thr=10000, double iir_coeff_prev=0.5,
double iir_coeff_new=0.5 ); double iir_coeff_new=0.5 );
~DigitalFilter (); ~DigitalFilter ();
// T <=0 - отключить вторую ступень фильтра // T <=0 - отключить вторую ступень фильтра
void setSettings( unsigned int bufsize, double T, double lsq, void setSettings( unsigned int bufsize, double T, double lsq,
int iir_thr, double iir_coeff_prev, double iir_coeff_new ); int iir_thr, double iir_coeff_prev, double iir_coeff_new );
...@@ -26,13 +26,13 @@ class DigitalFilter ...@@ -26,13 +26,13 @@ class DigitalFilter
// возвращается фильтрованное с учётом // возвращается фильтрованное с учётом
// предыдущих значений... // предыдущих значений...
int filter1( int newValue ); int filter1( int newValue );
// RC-фильтр // RC-фильтр
int filterRC( int newVal ); int filterRC( int newVal );
// медианный фильтр // медианный фильтр
int median( int newval ); int median( int newval );
// адаптивный фильтр по схеме наименьших квадратов // адаптивный фильтр по схеме наименьших квадратов
int leastsqr( int newval ); int leastsqr( int newval );
...@@ -50,9 +50,9 @@ class DigitalFilter ...@@ -50,9 +50,9 @@ class DigitalFilter
void add( int newValue ); void add( int newValue );
void init( int val ); void init( int val );
// void init( list<int>& data ); // void init( list<int>& data );
inline int size(){ return buf.size(); } inline int size(){ return buf.size(); }
inline double middle(){ return M; } inline double middle(){ return M; }
...@@ -60,7 +60,7 @@ class DigitalFilter ...@@ -60,7 +60,7 @@ class DigitalFilter
friend std::ostream& operator<<(std::ostream& os, const DigitalFilter& d); friend std::ostream& operator<<(std::ostream& os, const DigitalFilter& d);
friend std::ostream& operator<<(std::ostream& os, const DigitalFilter* d); friend std::ostream& operator<<(std::ostream& os, const DigitalFilter* d);
private: private:
// Первая ступень фильтра // Первая ступень фильтра
...@@ -73,11 +73,11 @@ class DigitalFilter ...@@ -73,11 +73,11 @@ class DigitalFilter
double M; // Среднее арифметическое double M; // Среднее арифметическое
double S; // Среднеквадратичное отклонение double S; // Среднеквадратичное отклонение
PassiveTimer tmr; PassiveTimer tmr;
typedef std::list<int> FIFOBuffer; typedef std::deque<int> FIFOBuffer;
FIFOBuffer buf; FIFOBuffer buf;
unsigned int maxsize; unsigned int maxsize;
typedef std::vector<int> MedianVector; typedef std::vector<int> MedianVector;
MedianVector mvec; MedianVector mvec;
......
...@@ -107,10 +107,10 @@ minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftR ...@@ -107,10 +107,10 @@ minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftR
pvec(50), pvec(50),
myname(""), myname(""),
szCache(5), szCache(5),
cache(5), numCacheResort(20),
numCacheResort(5),
numCallToCache(5) numCallToCache(5)
{ {
cache.assign(szCache,CacheInfo());
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
...@@ -120,10 +120,10 @@ minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftR ...@@ -120,10 +120,10 @@ minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftR
pvec(50), pvec(50),
myname(name), myname(name),
szCache(5), szCache(5),
cache(5), numCacheResort(20),
numCacheResort(5),
numCallToCache(5) numCallToCache(5)
{ {
cache.assign(szCache,CacheInfo());
build(name,confile,0); build(name,confile,0);
} }
...@@ -131,10 +131,10 @@ numCallToCache(5) ...@@ -131,10 +131,10 @@ numCallToCache(5)
Calibration::Calibration( xmlNode* node ): Calibration::Calibration( xmlNode* node ):
minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftRaw(0),pvec(100), minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftRaw(0),pvec(100),
szCache(5), szCache(5),
cache(5), numCacheResort(20),
numCacheResort(5),
numCallToCache(5) numCallToCache(5)
{ {
cache.assign(szCache,CacheInfo());
UniXML_iterator it(node); UniXML_iterator it(node);
myname = it.getProp("name"); myname = it.getProp("name");
build("","",node); build("","",node);
...@@ -188,7 +188,7 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo ...@@ -188,7 +188,7 @@ void Calibration::build( const string& name, const string& confile, xmlNode* roo
if( p.x==0 || p.y==0 ) if( p.x==0 || p.y==0 )
{ {
cerr << myname << "(Calibration::build): (warn) x=" cerr << myname << "(Calibration::build): (warn) x="
<< p.x << " y=" << p.y << endl; << p.x << " y=" << p.y << endl;
} }
...@@ -326,10 +326,9 @@ void Calibration::setCacheSize( unsigned int sz ) ...@@ -326,10 +326,9 @@ void Calibration::setCacheSize( unsigned int sz )
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
void Calibration::insertToCache( const long raw, const long val ) void Calibration::insertToCache( const long raw, const long val )
{ {
sort(cache.begin(),cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< )
cache.pop_back(); // удаляем последний элемент (как самый неиспользуемый) cache.pop_back(); // удаляем последний элемент (как самый неиспользуемый)
cache.push_back( CacheInfo(raw,val) ); // добавляем в конец.. cache.push_back( CacheInfo(raw,val) ); // добавляем в конец..
sort(cache.begin(),cache.end()); // пересортируем с учётом вставки sort(cache.begin(),cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< )
} }
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
long Calibration::getRawValue( long cal, bool range ) long Calibration::getRawValue( long cal, bool range )
......
...@@ -27,6 +27,9 @@ DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq, ...@@ -27,6 +27,9 @@ DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq,
coeff_prev(iir_coeff_prev), coeff_prev(iir_coeff_prev),
coeff_new(iir_coeff_new) coeff_new(iir_coeff_new)
{ {
buf.resize(maxsize);
mvec.reserve(maxsize);
init(val);
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
DigitalFilter::~DigitalFilter() DigitalFilter::~DigitalFilter()
...@@ -41,7 +44,7 @@ void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq, ...@@ -41,7 +44,7 @@ void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq,
maxsize = bufsize; maxsize = bufsize;
if( maxsize < 1 ) if( maxsize < 1 )
maxsize = 1; maxsize = 1;
coeff_prev = iir_coeff_prev; coeff_prev = iir_coeff_prev;
coeff_new = iir_coeff_new; coeff_new = iir_coeff_new;
if( iir_thr > 0 ) if( iir_thr > 0 )
...@@ -52,13 +55,14 @@ void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq, ...@@ -52,13 +55,14 @@ void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq,
// удаляем лишние (первые) элементы // удаляем лишние (первые) элементы
int sub = buf.size() - maxsize; int sub = buf.size() - maxsize;
for( unsigned int i=0; i<sub; i++ ) for( unsigned int i=0; i<sub; i++ )
buf.erase( buf.begin() ); buf.pop_front();
} }
buf.resize(maxsize);
if( w.size() != maxsize || lsq != lsparam ) if( w.size() != maxsize || lsq != lsparam )
w.assign(maxsize, 1.0/maxsize); w.assign(maxsize, 1.0/maxsize);
lsparam = lsq;
lsparam = lsq;
mvec.resize(maxsize); mvec.resize(maxsize);
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
...@@ -86,7 +90,7 @@ double DigitalFilter::firstLevel() ...@@ -86,7 +90,7 @@ double DigitalFilter::firstLevel()
// считаем среднеквадратичное отклонение // считаем среднеквадратичное отклонение
S=0; S=0;
double r=0; double r=0;
for( FIFOBuffer::iterator i=buf.begin(); i!=buf.end(); ++i ) for( FIFOBuffer::iterator i=buf.begin(); i!=buf.end(); ++i )
{ {
r = M-(*i); r = M-(*i);
S = S + r*r; S = S + r*r;
...@@ -156,9 +160,13 @@ void DigitalFilter::add( int newval ) ...@@ -156,9 +160,13 @@ void DigitalFilter::add( int newval )
{ {
// помещаем очередное значение в буфер // помещаем очередное значение в буфер
// удаляя при этом старое (FIFO) // удаляя при этом старое (FIFO)
// т.к. мы изначально создаём буфер нужного размера и заполням (см. init)
// то каждый раз проверять размер не нужно
// if( buf.size() > maxsize )
// buf.pop_front();
buf.pop_front();
buf.push_back(newval); buf.push_back(newval);
if( buf.size() > maxsize )
buf.erase( buf.begin() );
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
int DigitalFilter::current1() int DigitalFilter::current1()
...@@ -174,7 +182,7 @@ int DigitalFilter::currentRC() ...@@ -174,7 +182,7 @@ int DigitalFilter::currentRC()
std::ostream& operator<<(std::ostream& os, const DigitalFilter& d ) std::ostream& operator<<(std::ostream& os, const DigitalFilter& d )
{ {
os << "(" << d.buf.size() << ")["; os << "(" << d.buf.size() << ")[";
for( DigitalFilter::FIFOBuffer::const_iterator i=d.buf.begin(); i!=d.buf.end(); ++i ) for( DigitalFilter::FIFOBuffer::const_iterator i=d.buf.begin(); i!=d.buf.end(); ++i )
{ {
os << " " << setw(5) << (*i); os << " " << setw(5) << (*i);
} }
......
...@@ -6,6 +6,9 @@ ...@@ -6,6 +6,9 @@
#include "Extensions.h" #include "Extensions.h"
#include "Calibration.h" #include "Calibration.h"
#include <vector>
#include <deque>
using namespace std; using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
using namespace UniSetExtensions; using namespace UniSetExtensions;
...@@ -24,6 +27,12 @@ int main( int argc, const char** argv ) ...@@ -24,6 +27,12 @@ int main( int argc, const char** argv )
cout << "-540 --> " << cal->getValue(-540) << endl; cout << "-540 --> " << cal->getValue(-540) << endl;
cout << "-320 --> " << cal->getValue(-320) << endl; cout << "-320 --> " << cal->getValue(-320) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl; cout << "-200 --> " << cal->getValue(-200) << endl;
// проверка кэша....
cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
// --------------
cout << "-100 --> " << cal->getValue(-100) << endl; cout << "-100 --> " << cal->getValue(-100) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl; cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-100 --> " << cal->getValue(-100) << endl; cout << "-100 --> " << cal->getValue(-100) << endl;
......
...@@ -40,7 +40,7 @@ class IOController: ...@@ -40,7 +40,7 @@ class IOController:
public POA_IOController_i public POA_IOController_i
{ {
public: public:
IOController(const std::string& name, const std::string& section); IOController(const std::string& name, const std::string& section);
IOController(UniSetTypes::ObjectId id); IOController(UniSetTypes::ObjectId id);
~IOController(); ~IOController();
...@@ -91,7 +91,7 @@ class IOController: ...@@ -91,7 +91,7 @@ class IOController:
UniSetTypes::Message::Priority getPriority(const IOController_i::SensorInfo& si, UniSetTypes::Message::Priority getPriority(const IOController_i::SensorInfo& si,
UniversalIO::IOType type); UniversalIO::IOType type);
virtual IOController_i::ShortIOInfo getChangedTime(const IOController_i::SensorInfo& si); virtual IOController_i::ShortIOInfo getChangedTime(const IOController_i::SensorInfo& si);
virtual IOController_i::ShortMapSeq* getSensors(); virtual IOController_i::ShortMapSeq* getSensors();
......
...@@ -24,7 +24,7 @@ ...@@ -24,7 +24,7 @@
#ifndef Object_LT_H_ #ifndef Object_LT_H_
#define Object_LT_H_ #define Object_LT_H_
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
#include <list> #include <deque>
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "MessageType.h" #include "MessageType.h"
#include "PassiveTimer.h" #include "PassiveTimer.h"
...@@ -57,7 +57,6 @@ class UniSetObject; ...@@ -57,7 +57,6 @@ class UniSetObject;
int sleepTime; int sleepTime;
UniSetObject_LT lt; UniSetObject_LT lt;
void callback(); void callback();
} }
void callback() void callback()
...@@ -68,10 +67,10 @@ class UniSetObject; ...@@ -68,10 +67,10 @@ class UniSetObject;
// заказа продолжит спать(т.е. обработчик вызван не будет)... // заказа продолжит спать(т.е. обработчик вызван не будет)...
try try
{ {
if( waitMessage(msg, sleepTime) ) if( waitMessage(msg, sleepTime) )
processingMessage(&msg); processingMessage(&msg);
sleepTime=lt.checkTimers(this); sleepTime=lt.checkTimers(this);
} }
catch(Exception& ex) catch(Exception& ex)
...@@ -165,7 +164,7 @@ class LT_Object ...@@ -165,7 +164,7 @@ class LT_Object
class Timer_eq: public std::unary_function<TimerInfo, bool> class Timer_eq: public std::unary_function<TimerInfo, bool>
{ {
public: public:
Timer_eq(UniSetTypes::TimerId t):tid(t){} Timer_eq(UniSetTypes::TimerId t):tid(t){}
inline bool operator()(const TimerInfo& ti) const inline bool operator()(const TimerInfo& ti) const
...@@ -177,7 +176,7 @@ class LT_Object ...@@ -177,7 +176,7 @@ class LT_Object
UniSetTypes::TimerId tid; UniSetTypes::TimerId tid;
}; };
typedef std::list<TimerInfo> TimersList; typedef std::deque<TimerInfo> TimersList;
private: private:
TimersList tlst; TimersList tlst;
......
...@@ -25,11 +25,13 @@ ...@@ -25,11 +25,13 @@
#ifndef UniSetActivator_H_ #ifndef UniSetActivator_H_
#define UniSetActivator_H_ #define UniSetActivator_H_
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <deque>
#include <omniORB4/CORBA.h> #include <omniORB4/CORBA.h>
#include "UniSetTypes.h" #include "UniSetTypes.h"
#include "UniSetObject.h" #include "UniSetObject.h"
#include "UniSetManager.h" #include "UniSetManager.h"
#include "ThreadCreator.h" #include "ThreadCreator.h"
//#include "OmniThreadCreator.h" //#include "OmniThreadCreator.h"
//---------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------
/*! \class UniSetActivator /*! \class UniSetActivator
...@@ -61,7 +63,6 @@ class UniSetActivator: ...@@ -61,7 +63,6 @@ class UniSetActivator:
protected: protected:
/*! Команды доступные при заказе сигналов /*! Команды доступные при заказе сигналов
* см. askSignal() * см. askSignal()
*/ */
...@@ -91,7 +92,7 @@ class UniSetActivator: ...@@ -91,7 +92,7 @@ class UniSetActivator:
private: private:
// static void processingSignal(int signo); // static void processingSignal(int signo);
static void terminated(int signo); static void terminated(int signo);
static void finishterm(int signo); static void finishterm(int signo);
static void normalexit(); static void normalexit();
...@@ -102,10 +103,10 @@ class UniSetActivator: ...@@ -102,10 +103,10 @@ class UniSetActivator:
friend class ThreadCreator<UniSetActivator>; friend class ThreadCreator<UniSetActivator>;
ThreadCreator<UniSetActivator> *orbthr; ThreadCreator<UniSetActivator> *orbthr;
CORBA::ORB_var orb; CORBA::ORB_var orb;
bool omDestroy; bool omDestroy;
bool sig; bool sig;
pid_t thpid; // pid orb потока pid_t thpid; // pid orb потока
...@@ -126,9 +127,9 @@ class UniSetActivator: ...@@ -126,9 +127,9 @@ class UniSetActivator:
UniSetManager* mnr; UniSetManager* mnr;
}; };
std::list<OInfo> lstOInfo; std::deque<OInfo> lstOInfo;
std::list<MInfo> lstMInfo; std::deque<MInfo> lstMInfo;
void getinfo(); void getinfo();
}; };
/* /*
...@@ -138,7 +139,7 @@ int UniSetActivator::attach(TClass* p, void(TClass:: *f)(void*) ) ...@@ -138,7 +139,7 @@ int UniSetActivator::attach(TClass* p, void(TClass:: *f)(void*) )
if( next >= MAX_CHILD_THREAD ) if( next >= MAX_CHILD_THREAD )
return -1; return -1;
callpull[next] = new OmniThreadCreator<TClass>( p, f); callpull[next] = new OmniThreadCreator<TClass>( p, f);
next++; next++;
return 0; return 0;
} }
......
...@@ -1606,7 +1606,7 @@ IOController_i::CalibrateInfo UInterface::getCalibrateInfo( const IOController_i ...@@ -1606,7 +1606,7 @@ IOController_i::CalibrateInfo UInterface::getCalibrateInfo( const IOController_i
// -------------------------------------------------------------------------------------------- // --------------------------------------------------------------------------------------------
IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( UniSetTypes::IDList& lst ) IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( UniSetTypes::IDList& lst )
{ {
if( lst.size() == 0 ) if( lst.empty() )
return IOController_i::SensorInfoSeq_var(); return IOController_i::SensorInfoSeq_var();
ObjectId sid = lst.getFirst(); ObjectId sid = lst.getFirst();
...@@ -1761,7 +1761,7 @@ IDSeq_var UInterface::setOutputSeq( const IOController_i::OutSeq& lst, UniSetTyp ...@@ -1761,7 +1761,7 @@ IDSeq_var UInterface::setOutputSeq( const IOController_i::OutSeq& lst, UniSetTyp
UniSetTypes::IDSeq_var UInterface::askSensorsSeq( UniSetTypes::IDList& lst, UniSetTypes::IDSeq_var UInterface::askSensorsSeq( UniSetTypes::IDList& lst,
UniversalIO::UIOCommand cmd, UniSetTypes::ObjectId backid ) UniversalIO::UIOCommand cmd, UniSetTypes::ObjectId backid )
{ {
if( lst.size() == 0 ) if( lst.empty() )
return UniSetTypes::IDSeq_var(); return UniSetTypes::IDSeq_var();
if( backid==UniSetTypes::DefaultObjectId ) if( backid==UniSetTypes::DefaultObjectId )
......
...@@ -70,8 +70,8 @@ static UniSetActivator* gActivator=0; ...@@ -70,8 +70,8 @@ static UniSetActivator* gActivator=0;
static int SIGNO; static int SIGNO;
static int MYPID; static int MYPID;
static const int TERMINATE_TIMEOUT = 2; // время отведенное на завершение процесса [сек] static const int TERMINATE_TIMEOUT = 2; // время отведенное на завершение процесса [сек]
volatile sig_atomic_t procterm = 0; ost::AtomicCounter procterm = 0;
volatile sig_atomic_t doneterm = 0; ost::AtomicCounter doneterm = 0;
// PassiveTimer termtmr; // PassiveTimer termtmr;
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -353,7 +353,7 @@ void UniSetActivator::sig_child(int signo) ...@@ -353,7 +353,7 @@ void UniSetActivator::sig_child(int signo)
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetActivator::set_signals(bool ask) void UniSetActivator::set_signals(bool ask)
{ {
struct sigaction act, oact; struct sigaction act, oact;
sigemptyset(&act.sa_mask); sigemptyset(&act.sa_mask);
sigemptyset(&oact.sa_mask); sigemptyset(&oact.sa_mask);
...@@ -482,14 +482,9 @@ void UniSetActivator::term( int signo ) ...@@ -482,14 +482,9 @@ void UniSetActivator::term( int signo )
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetActivator::waitDestroy() void UniSetActivator::waitDestroy()
{ {
for(;;) while( !doneterm && gActivator )
{
if( doneterm || !gActivator )
break;
msleep(50); msleep(50);
}
gActivator = 0; gActivator = 0;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -259,7 +259,7 @@ using namespace UniSetTypes; ...@@ -259,7 +259,7 @@ using namespace UniSetTypes;
continue; continue;
} }
item.fname = s; item.fname = s;
std::list<std::string> t = UniSetTypes::explode_str(s,'@'); std::list<std::string> t = UniSetTypes::explode_str(s,'@');
if( t.size() == 1 ) if( t.size() == 1 )
{ {
......
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
*/ */
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#include <sstream> #include <sstream>
#include <algorithm>
#include "Exceptions.h" #include "Exceptions.h"
#include "UniSetObject.h" #include "UniSetObject.h"
#include "LT_Object.h" #include "LT_Object.h"
...@@ -50,7 +51,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj ) ...@@ -50,7 +51,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
{ {
{ // lock { // lock
uniset_rwmutex_rlock lock(lstMutex); uniset_rwmutex_rlock lock(lstMutex);
if( tlst.empty() ) if( tlst.empty() )
{ {
sleepTime = UniSetTimer::WaitUpTime; sleepTime = UniSetTimer::WaitUpTime;
...@@ -73,14 +74,14 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj ) ...@@ -73,14 +74,14 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
{ // lock { // lock
uniset_rwmutex_wrlock lock(lstMutex); uniset_rwmutex_wrlock lock(lstMutex);
sleepTime = UniSetTimer::WaitUpTime; sleepTime = UniSetTimer::WaitUpTime;
for( TimersList::iterator li=tlst.begin();li!=tlst.end();++li) for( TimersList::iterator li=tlst.begin(); li!=tlst.end(); ++li )
{ {
if( li->tmr.checkTime() ) if( li->tmr.checkTime() )
{ {
// помещаем себе в очередь сообщение // помещаем себе в очередь сообщение
TransportMessage tm = TimerMessage(li->id, li->priority, obj->getId()).transport_msg(); TransportMessage tm = TimerMessage(li->id, li->priority, obj->getId()).transport_msg();
obj->push(tm); obj->push(tm);
// Проверка на количество заданных тактов // Проверка на количество заданных тактов
if( !li->curTick ) if( !li->curTick )
{ {
...@@ -104,19 +105,19 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj ) ...@@ -104,19 +105,19 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
// ищем минимальное оставшееся время // ищем минимальное оставшееся время
if( li->curTimeMS < sleepTime || sleepTime == UniSetTimer::WaitUpTime ) if( li->curTimeMS < sleepTime || sleepTime == UniSetTimer::WaitUpTime )
sleepTime = li->curTimeMS; sleepTime = li->curTimeMS;
} }
if( sleepTime < UniSetTimer::MinQuantityTime ) if( sleepTime < UniSetTimer::MinQuantityTime )
sleepTime=UniSetTimer::MinQuantityTime; sleepTime=UniSetTimer::MinQuantityTime;
} // unlock } // unlock
tmLast.reset(); tmLast.reset();
} }
catch(Exception& ex) catch( Exception& ex )
{ {
ucrit << "(checkTimers): " << ex << endl; ucrit << "(checkTimers): " << ex << endl;
} }
return sleepTime; return sleepTime;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -161,11 +162,11 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c ...@@ -161,11 +162,11 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c
{ {
uinfo << "(LT_askTimer): поступил отказ по таймеру id="<< timerid << endl; uinfo << "(LT_askTimer): поступил отказ по таймеру id="<< timerid << endl;
{ // lock { // lock
uniset_rwmutex_wrlock lock(lstMutex); uniset_rwmutex_wrlock lock(lstMutex);
tlst.remove_if(Timer_eq(timerid)); // STL - способ tlst.erase( std::remove_if(tlst.begin(),tlst.end(),Timer_eq(timerid)) );
} // unlock } // unlock
} }
{ // lock { // lock
uniset_rwmutex_rlock lock(lstMutex); uniset_rwmutex_rlock lock(lstMutex);
......
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