Commit afa40939 authored by Pavel Vainerman's avatar Pavel Vainerman

(Mutex): ПЕРЕХОД НА RWMUTEX-Ы ВЕЗДЕ ГДЕ МОЖНО

parent 3b35d826
...@@ -121,7 +121,7 @@ ...@@ -121,7 +121,7 @@
<UNetExchange name="UNetExchange"/> <UNetExchange name="UNetExchange"/>
<HeartBeatTime time_msec="5000"/> <HeartBeatTime time_msec="5000"/>
<TestGen input1_s="Input1_S" input2_s="DumpSensor1_S" name="TestGen" output1_c="DO_C"/> <TestGen input1_s="Input1_S" input2_s="DumpSensor1_S" name="TestGen" output1_c="DO_C"/>
<RRDStorage1 name="RRDStorage1"> <RRDServer1 name="RRDServer1">
<rrd filename="rrdtest.rrd" filter_field="rrd" filter_value="1" step="5" ds_field="rrd1_ds" overwrite="0"> <rrd filename="rrdtest.rrd" filter_field="rrd" filter_value="1" step="5" ds_field="rrd1_ds" overwrite="0">
<item rra="RRA:AVERAGE:0.5:1:4320"/> <item rra="RRA:AVERAGE:0.5:1:4320"/>
<item rra="RRA:MAX:0.5:1:4320"/> <item rra="RRA:MAX:0.5:1:4320"/>
...@@ -130,7 +130,7 @@ ...@@ -130,7 +130,7 @@
<item rra="RRA:AVERAGE:0.5:1:4320"/> <item rra="RRA:AVERAGE:0.5:1:4320"/>
<item rra="RRA:MAX:0.5:1:4320"/> <item rra="RRA:MAX:0.5:1:4320"/>
</rrd> </rrd>
</RRDStorage1> </RRDServer1>
</settings> </settings>
<ObjectsMap idfromfile="0"> <ObjectsMap idfromfile="0">
<!-- <!--
...@@ -243,7 +243,7 @@ ...@@ -243,7 +243,7 @@
<item id="6008" name="UNetExchange"/> <item id="6008" name="UNetExchange"/>
<item id="6009" name="MBMaster2"/> <item id="6009" name="MBMaster2"/>
<item id="6010" name="MBMultiMaster1"/> <item id="6010" name="MBMultiMaster1"/>
<item id="6011" name="RRDStorage1"/> <item id="6011" name="RRDServer1"/>
</objects> </objects>
</ObjectsMap> </ObjectsMap>
<messages idfromfile="1" name="messages"> <messages idfromfile="1" name="messages">
......
...@@ -53,6 +53,8 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id): ...@@ -53,6 +53,8 @@ DBServer_MySQL::DBServer_MySQL(ObjectId id):
msg << "(DBServer_MySQL): init failed! Unknown ID!" << endl; msg << "(DBServer_MySQL): init failed! Unknown ID!" << endl;
throw Exception(msg.str()); throw Exception(msg.str());
} }
mqbuf.setName(myname + "_qbufMutex");
} }
DBServer_MySQL::DBServer_MySQL(): DBServer_MySQL::DBServer_MySQL():
...@@ -72,6 +74,8 @@ DBServer_MySQL::DBServer_MySQL(): ...@@ -72,6 +74,8 @@ DBServer_MySQL::DBServer_MySQL():
msg << "(DBServer_MySQL): init failed! Unknown ID!" << endl; msg << "(DBServer_MySQL): init failed! Unknown ID!" << endl;
throw Exception(msg.str()); throw Exception(msg.str());
} }
mqbuf.setName(myname + "_qbufMutex");
} }
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
DBServer_MySQL::~DBServer_MySQL() DBServer_MySQL::~DBServer_MySQL()
...@@ -206,7 +210,7 @@ bool DBServer_MySQL::writeToBase( const string& query ) ...@@ -206,7 +210,7 @@ bool DBServer_MySQL::writeToBase( const string& query )
// cout << "DBServer_MySQL: " << query << endl; // cout << "DBServer_MySQL: " << query << endl;
if( !db || !connect_ok ) if( !db || !connect_ok )
{ {
uniset_mutex_lock l(mqbuf,200); uniset_rwmutex_wrlock l(mqbuf);
qbuf.push(query); qbuf.push(query);
if( qbuf.size() > qbufSize ) if( qbuf.size() > qbufSize )
{ {
...@@ -247,7 +251,7 @@ bool DBServer_MySQL::writeToBase( const string& query ) ...@@ -247,7 +251,7 @@ bool DBServer_MySQL::writeToBase( const string& query )
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_MySQL::flushBuffer() void DBServer_MySQL::flushBuffer()
{ {
uniset_mutex_lock l(mqbuf,400); uniset_rwmutex_wrlock l(mqbuf);
// Сперва пробуем очистить всё что накопилось в очереди до этого... // Сперва пробуем очистить всё что накопилось в очереди до этого...
while( !qbuf.empty() ) while( !qbuf.empty() )
......
...@@ -187,7 +187,7 @@ class DBServer_MySQL: ...@@ -187,7 +187,7 @@ class DBServer_MySQL:
bool lastRemove; bool lastRemove;
void flushBuffer(); void flushBuffer();
UniSetTypes::uniset_mutex mqbuf; UniSetTypes::uniset_rwmutex mqbuf;
private: private:
DBTableMap tblMap; DBTableMap tblMap;
......
...@@ -203,7 +203,7 @@ bool DBServer_SQLite::writeToBase( const string& query ) ...@@ -203,7 +203,7 @@ bool DBServer_SQLite::writeToBase( const string& query )
// cout << "DBServer_SQLite: " << query << endl; // cout << "DBServer_SQLite: " << query << endl;
if( !db || !connect_ok ) if( !db || !connect_ok )
{ {
uniset_mutex_lock l(mqbuf,200); uniset_rwmutex_wrlock l(mqbuf);
qbuf.push(query); qbuf.push(query);
if( qbuf.size() > qbufSize ) if( qbuf.size() > qbufSize )
{ {
...@@ -234,7 +234,7 @@ bool DBServer_SQLite::writeToBase( const string& query ) ...@@ -234,7 +234,7 @@ bool DBServer_SQLite::writeToBase( const string& query )
//-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------
void DBServer_SQLite::flushBuffer() void DBServer_SQLite::flushBuffer()
{ {
uniset_mutex_lock l(mqbuf,400); uniset_rwmutex_wrlock l(mqbuf);
// Сперва пробуем очистить всё что накопилось в очереди до этого... // Сперва пробуем очистить всё что накопилось в очереди до этого...
while( !qbuf.empty() ) while( !qbuf.empty() )
......
...@@ -187,7 +187,7 @@ class DBServer_SQLite: ...@@ -187,7 +187,7 @@ class DBServer_SQLite:
bool lastRemove; bool lastRemove;
void flushBuffer(); void flushBuffer();
UniSetTypes::uniset_mutex mqbuf; UniSetTypes::uniset_rwmutex mqbuf;
private: private:
DBTableMap tblMap; DBTableMap tblMap;
......
...@@ -557,7 +557,7 @@ void IOControl::ioread( IOInfo* it ) ...@@ -557,7 +557,7 @@ void IOControl::ioread( IOInfo* it )
} }
else // управление лампочками else // управление лампочками
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
long prev_val = it->value; long prev_val = it->value;
if( force_out ) if( force_out )
it->value = shm->localGetValue(it->ait,it->si.id); it->value = shm->localGetValue(it->ait,it->si.id);
...@@ -1425,7 +1425,7 @@ void IOControl::sensorInfo( UniSetTypes::SensorMessage* sm ) ...@@ -1425,7 +1425,7 @@ void IOControl::sensorInfo( UniSetTypes::SensorMessage* sm )
long prev_val = 0; long prev_val = 0;
long cur_val = 0; long cur_val = 0;
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
prev_val = it->value; prev_val = it->value;
it->value = sm->value; it->value = sm->value;
cur_val = sm->value; cur_val = sm->value;
...@@ -1520,7 +1520,7 @@ void IOControl::sensorInfo( UniSetTypes::SensorMessage* sm ) ...@@ -1520,7 +1520,7 @@ void IOControl::sensorInfo( UniSetTypes::SensorMessage* sm )
dlog[Debug::LEVEL1] << myname << "(sensorInfo): DO: sm->id=" << sm->id dlog[Debug::LEVEL1] << myname << "(sensorInfo): DO: sm->id=" << sm->id
<< " val=" << sm->value << endl; << " val=" << sm->value << endl;
} }
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
it->value = sm->state ? 1:0; it->value = sm->state ? 1:0;
} }
break; break;
......
...@@ -36,6 +36,8 @@ pollActivated(false) ...@@ -36,6 +36,8 @@ pollActivated(false)
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBExchange): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(MBExchange): objId=-1?!! Use --" + prefix + "-name" );
mutex_start.setName(myname + "_mutex_start");
// xmlNode* cnode = conf->getNode(myname); // xmlNode* cnode = conf->getNode(myname);
string conf_name = conf->getArgParam("--" + prefix + "-confnode",myname); string conf_name = conf->getArgParam("--" + prefix + "-confnode",myname);
...@@ -225,13 +227,13 @@ void MBExchange::step() ...@@ -225,13 +227,13 @@ void MBExchange::step()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool MBExchange::checkProcActive() bool MBExchange::checkProcActive()
{ {
uniset_mutex_lock l(actMutex, 300); uniset_rwmutex_rlock l(actMutex);
return activated; return activated;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void MBExchange::setProcActive( bool st ) void MBExchange::setProcActive( bool st )
{ {
uniset_mutex_lock l(actMutex, 400); uniset_rwmutex_wrlock l(actMutex);
activated = st; activated = st;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
...@@ -2417,7 +2419,7 @@ bool MBExchange::activateObject() ...@@ -2417,7 +2419,7 @@ bool MBExchange::activateObject()
// см. sysCommand() // см. sysCommand()
{ {
setProcActive(false); setProcActive(false);
UniSetTypes::uniset_mutex_lock l(mutex_start, 5000); UniSetTypes::uniset_rwmutex_rlock l(mutex_start);
UniSetObject_LT::activateObject(); UniSetObject_LT::activateObject();
if( !shm->isLocalwork() ) if( !shm->isLocalwork() )
rtuQueryOptimization(rmap); rtuQueryOptimization(rmap);
...@@ -2511,7 +2513,7 @@ void MBExchange::sysCommand( UniSetTypes::SystemMessage *sm ) ...@@ -2511,7 +2513,7 @@ void MBExchange::sysCommand( UniSetTypes::SystemMessage *sm )
dlog[Debug::CRIT] << myname << "(sysCommand): ************* don`t activate?! ************" << endl; dlog[Debug::CRIT] << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
{ {
UniSetTypes::uniset_mutex_lock l(mutex_start, 10000); UniSetTypes::uniset_rwmutex_rlock l(mutex_start);
askSensors(UniversalIO::UIONotify); askSensors(UniversalIO::UIONotify);
initOutput(); initOutput();
} }
......
...@@ -281,7 +281,7 @@ class MBExchange: ...@@ -281,7 +281,7 @@ class MBExchange:
SMInterface* shm; SMInterface* shm;
bool initPause; bool initPause;
UniSetTypes::uniset_mutex mutex_start; UniSetTypes::uniset_rwmutex mutex_start;
bool force; /*!< флаг означающий, что надо сохранять в SM, даже если значение не менялось */ bool force; /*!< флаг означающий, что надо сохранять в SM, даже если значение не менялось */
bool force_out; /*!< флаг означающий, принудительного чтения выходов */ bool force_out; /*!< флаг означающий, принудительного чтения выходов */
...@@ -299,7 +299,7 @@ class MBExchange: ...@@ -299,7 +299,7 @@ class MBExchange:
IOController::AIOStateList::iterator aitExchangeMode; IOController::AIOStateList::iterator aitExchangeMode;
long exchangeMode; /*!< режим работы см. ExchangeMode */ long exchangeMode; /*!< режим работы см. ExchangeMode */
UniSetTypes::uniset_mutex actMutex; UniSetTypes::uniset_rwmutex actMutex;
bool activated; bool activated;
int activateTimeout; int activateTimeout;
bool noQueryOptimization; bool noQueryOptimization;
......
...@@ -207,7 +207,7 @@ class MBTCPMaster: ...@@ -207,7 +207,7 @@ class MBTCPMaster:
protected: protected:
virtual void sysCommand( UniSetTypes::SystemMessage *sm ); virtual void sysCommand( UniSetTypes::SystemMessage *sm );
UniSetTypes::uniset_mutex mbMutex; UniSetTypes::uniset_rwmutex mbMutex;
std::string iaddr; std::string iaddr;
// ost::InetAddress* ia; // ost::InetAddress* ia;
int port; int port;
...@@ -227,7 +227,7 @@ class MBTCPMaster: ...@@ -227,7 +227,7 @@ class MBTCPMaster:
// т.к. TCP может "зависнуть" на подключении к недоступному узлу // т.к. TCP может "зависнуть" на подключении к недоступному узлу
// делаем опрос в отдельном потоке // делаем опрос в отдельном потоке
ThreadCreator<MBTCPMaster>* pollThread; /*!< поток опроса */ ThreadCreator<MBTCPMaster>* pollThread; /*!< поток опроса */
UniSetTypes::uniset_mutex tcpMutex; UniSetTypes::uniset_rwmutex tcpMutex;
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // _MBTCPMaster_H_ #endif // _MBTCPMaster_H_
......
...@@ -17,6 +17,8 @@ force_disconnect(true), ...@@ -17,6 +17,8 @@ force_disconnect(true),
pollThread(0), pollThread(0),
checkThread(0) checkThread(0)
{ {
tcpMutex.setName(myname+"_tcpMutex");
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBTCPMultiMaster): objId=-1?!! Use --" + prefix + "-name" ); throw UniSetTypes::SystemError("(MBTCPMultiMaster): objId=-1?!! Use --" + prefix + "-name" );
...@@ -179,7 +181,7 @@ ModbusClient* MBTCPMultiMaster::initMB( bool reopen ) ...@@ -179,7 +181,7 @@ ModbusClient* MBTCPMultiMaster::initMB( bool reopen )
} }
{ {
uniset_mutex_lock l(tcpMutex,100); uniset_rwmutex_wrlock l(tcpMutex);
// Если по текущему каналу связь есть, то возвращаем его // Если по текущему каналу связь есть, то возвращаем его
if( mbi!=mblist.rend() && mbi->respond ) if( mbi!=mblist.rend() && mbi->respond )
{ {
...@@ -197,7 +199,7 @@ ModbusClient* MBTCPMultiMaster::initMB( bool reopen ) ...@@ -197,7 +199,7 @@ ModbusClient* MBTCPMultiMaster::initMB( bool reopen )
// проходим по списку (в обратном порядке, т.к. самый приоритетный в конце) // проходим по списку (в обратном порядке, т.к. самый приоритетный в конце)
for( MBGateList::reverse_iterator it=mblist.rbegin(); it!=mblist.rend(); ++it ) for( MBGateList::reverse_iterator it=mblist.rbegin(); it!=mblist.rend(); ++it )
{ {
uniset_mutex_lock l(tcpMutex,100); uniset_rwmutex_wrlock l(tcpMutex);
if( it->respond && it->init() ) if( it->respond && it->init() )
{ {
mbi = it; mbi = it;
...@@ -207,7 +209,7 @@ ModbusClient* MBTCPMultiMaster::initMB( bool reopen ) ...@@ -207,7 +209,7 @@ ModbusClient* MBTCPMultiMaster::initMB( bool reopen )
} }
{ {
uniset_mutex_lock l(tcpMutex,100); uniset_rwmutex_wrlock l(tcpMutex);
mbi = mblist.rend(); mbi = mblist.rend();
mb = 0; mb = 0;
} }
...@@ -329,8 +331,8 @@ void MBTCPMultiMaster::check_thread() ...@@ -329,8 +331,8 @@ void MBTCPMultiMaster::check_thread()
catch(...){} catch(...){}
{ {
uniset_mutex_lock l(tcpMutex,130); uniset_rwmutex_wrlock l(tcpMutex);
it->respond = r; it->respond = r;
} }
} }
......
...@@ -233,7 +233,7 @@ class MBTCPMultiMaster: ...@@ -233,7 +233,7 @@ class MBTCPMultiMaster:
void poll_thread(); void poll_thread();
void check_thread(); void check_thread();
UniSetTypes::uniset_mutex mbMutex; UniSetTypes::uniset_rwmutex mbMutex;
int recv_timeout; int recv_timeout;
bool force_disconnect; bool force_disconnect;
int checktime; int checktime;
...@@ -285,7 +285,7 @@ class MBTCPMultiMaster: ...@@ -285,7 +285,7 @@ class MBTCPMultiMaster:
// т.к. TCP может "зависнуть" на подключении к недоступному узлу // т.к. TCP может "зависнуть" на подключении к недоступному узлу
// делаем опрос в отдельном потоке // делаем опрос в отдельном потоке
ThreadCreator<MBTCPMultiMaster>* pollThread; /*!< поток опроса */ ThreadCreator<MBTCPMultiMaster>* pollThread; /*!< поток опроса */
UniSetTypes::uniset_mutex tcpMutex; UniSetTypes::uniset_rwmutex tcpMutex;
ThreadCreator<MBTCPMultiMaster>* checkThread; /*!< поток проверки связи по другим каналам */ ThreadCreator<MBTCPMultiMaster>* checkThread; /*!< поток проверки связи по другим каналам */
}; };
......
...@@ -32,6 +32,8 @@ prefix(prefix) ...@@ -32,6 +32,8 @@ prefix(prefix)
if( objId == DefaultObjectId ) if( objId == DefaultObjectId )
throw UniSetTypes::SystemError("(MBSlave): objId=-1?!! Use --mbs-name" ); throw UniSetTypes::SystemError("(MBSlave): objId=-1?!! Use --mbs-name" );
mutex_start.setName(myname + "_mutex_start");
// xmlNode* cnode = conf->getNode(myname); // xmlNode* cnode = conf->getNode(myname);
cnode = conf->getNode(myname); cnode = conf->getNode(myname);
if( cnode == NULL ) if( cnode == NULL )
...@@ -608,7 +610,7 @@ void MBSlave::sysCommand(UniSetTypes::SystemMessage *sm) ...@@ -608,7 +610,7 @@ void MBSlave::sysCommand(UniSetTypes::SystemMessage *sm)
dlog[Debug::CRIT] << myname << "(sysCommand): ************* don`t activate?! ************" << endl; dlog[Debug::CRIT] << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
else else
{ {
UniSetTypes::uniset_mutex_lock l(mutex_start, 10000); UniSetTypes::uniset_rwmutex_rlock l(mutex_start);
askSensors(UniversalIO::UIONotify); askSensors(UniversalIO::UIONotify);
thr->start(); thr->start();
} }
...@@ -709,13 +711,13 @@ void MBSlave::sensorInfo( UniSetTypes::SensorMessage* sm ) ...@@ -709,13 +711,13 @@ void MBSlave::sensorInfo( UniSetTypes::SensorMessage* sm )
if( p->stype == UniversalIO::DigitalOutput || if( p->stype == UniversalIO::DigitalOutput ||
p->stype == UniversalIO::DigitalInput ) p->stype == UniversalIO::DigitalInput )
{ {
uniset_spin_lock lock(p->val_lock); uniset_rwmutex_wrlock lock(p->val_lock);
p->value = sm->state ? 1 : 0; p->value = sm->state ? 1 : 0;
} }
else if( p->stype == UniversalIO::AnalogOutput || else if( p->stype == UniversalIO::AnalogOutput ||
p->stype == UniversalIO::AnalogInput ) p->stype == UniversalIO::AnalogInput )
{ {
uniset_spin_lock lock(p->val_lock); uniset_rwmutex_wrlock lock(p->val_lock);
p->value = sm->value; p->value = sm->value;
} }
...@@ -754,7 +756,7 @@ bool MBSlave::activateObject() ...@@ -754,7 +756,7 @@ bool MBSlave::activateObject()
// см. sysCommand() // см. sysCommand()
{ {
activated = false; activated = false;
UniSetTypes::uniset_mutex_lock l(mutex_start, 5000); UniSetTypes::uniset_rwmutex_wrlock l(mutex_start);
UniSetObject_LT::activateObject(); UniSetObject_LT::activateObject();
initIterators(); initIterators();
activated = true; activated = true;
......
...@@ -130,7 +130,7 @@ class MBSlave: ...@@ -130,7 +130,7 @@ class MBSlave:
ModbusServerSlot* mbslot; ModbusServerSlot* mbslot;
ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */ ModbusRTU::ModbusAddr addr; /*!< адрес данного узла */
UniSetTypes::uniset_mutex mbMutex; UniSetTypes::uniset_rwmutex mbMutex;
xmlNode* cnode; xmlNode* cnode;
std::string s_field; std::string s_field;
...@@ -168,7 +168,7 @@ class MBSlave: ...@@ -168,7 +168,7 @@ class MBSlave:
private: private:
MBSlave(); MBSlave();
bool initPause; bool initPause;
UniSetTypes::uniset_mutex mutex_start; UniSetTypes::uniset_rwmutex mutex_start;
ThreadCreator<MBSlave>* thr; ThreadCreator<MBSlave>* thr;
PassiveTimer ptHeartBeat; PassiveTimer ptHeartBeat;
......
#!/bin/sh #!/bin/sh
uniset-start.sh -f ./uniset-mbslave --confile test.xml --dlog-add-levels info,crit,warn \ uniset-start.sh -f ./uniset-mbslave --confile test.xml --dlog-add-levels info,crit,warn \
--smemory-id SharedMemory \
--mbs-name MBSlave1 \ --mbs-name MBSlave1 \
--mbs-type TCP --mbs-inet-addr 127.0.0.1 --mbs-inet-port 2048 --mbs-reg-from-id 1 --mbs-my-addr 0x01 \ --mbs-type TCP --mbs-inet-addr 127.0.0.1 --mbs-inet-port 2048 --mbs-reg-from-id 1 --mbs-my-addr 0x01 \
--mbs-askcount-id SVU_AskCount_AS --mbs-respond-id RespondRTU_S --mbs-respond-invert 1 --mbs-askcount-id SVU_AskCount_AS --mbs-respond-id RespondRTU_S --mbs-respond-invert 1
......
...@@ -6,8 +6,8 @@ bin_PROGRAMS = @PACKAGE@-rrdserver ...@@ -6,8 +6,8 @@ bin_PROGRAMS = @PACKAGE@-rrdserver
RRD_VER=@LIBVER@ RRD_VER=@LIBVER@
lib_LTLIBRARIES = libUniSetRRDServer.la lib_LTLIBRARIES = libUniSetRRDServer.la
libUniSetRRDServer_la_LDFLAGS = -version-info $(RRD_VER) libUniSetRRDServer_la_LDFLAGS = -version-info $(RRD_VER)
libUniSetRRDServer_la_LIBADD = $(top_builddir)/lib/libUniSet.la \ libUniSetRRDServer_la_LIBADD = $(top_builddir)/lib/libUniSet.la \
$(top_builddir)/extensions/SharedMemory/libUniSetSharedMemory.la \ $(top_builddir)/extensions/SharedMemory/libUniSetSharedMemory.la \
$(top_builddir)/extensions/lib/libUniSetExtensions.la \ $(top_builddir)/extensions/lib/libUniSetExtensions.la \
......
#!/bin/sh #!/bin/sh
uniset-start.sh -f ./uniset-rrdstorage --confile test.xml \ uniset-start.sh -f ./uniset-rrdserver --confile test.xml \
--rrd-name RRDStorage1 \ --rrd-name RRDServer1 \
--dlog-add-levels info,crit,warn --dlog-add-levels info,crit,warn
...@@ -23,7 +23,7 @@ void SharedMemory::help_print( int argc, const char* const* argv ) ...@@ -23,7 +23,7 @@ void SharedMemory::help_print( int argc, const char* const* argv )
cout << "--wdt-device - Использовать в качестве WDT указанный файл." << endl; cout << "--wdt-device - Использовать в качестве WDT указанный файл." << endl;
cout << "--heartbeat-node - Загружать heartbeat датчики для указанного узла." << endl; cout << "--heartbeat-node - Загружать heartbeat датчики для указанного узла." << endl;
cout << "--heartbeat-check-time - период проверки 'счётчиков'. По умолчанию 1000 мсек" << endl; cout << "--heartbeat-check-time - период проверки 'счётчиков'. По умолчанию 1000 мсек" << endl;
cout << "--lock-value-pause - пауза между проверкой spin-блокировки на значение" << endl; cout << "--lock-rvalue-pause-msec - пауза между проверкой rw-блокировки на разрешение чтения" << endl;
cout << "--e-filter - фильтр для считывания <eventlist>" << endl; cout << "--e-filter - фильтр для считывания <eventlist>" << endl;
cout << "--e-startup-pause - пауза перед посылкой уведомления о старте SM. (По умолчанию: 1500 мсек)." << endl; cout << "--e-startup-pause - пауза перед посылкой уведомления о старте SM. (По умолчанию: 1500 мсек)." << endl;
cout << "--activate-timeout - время ожидания активизации (По умолчанию: 15000 мсек)." << endl; cout << "--activate-timeout - время ожидания активизации (По умолчанию: 15000 мсек)." << endl;
...@@ -44,6 +44,9 @@ SharedMemory::SharedMemory( ObjectId id, string datafile, std::string confname ) ...@@ -44,6 +44,9 @@ SharedMemory::SharedMemory( ObjectId id, string datafile, std::string confname )
iotypePulsar(UniversalIO::DigitalInput), iotypePulsar(UniversalIO::DigitalInput),
msecPulsar(0) msecPulsar(0)
{ {
mutex_start.setName(myname + "_mutex_start");
mutex_act.setName(myname + "_mutex_act");
string cname(confname); string cname(confname);
if( cname.empty() ) if( cname.empty() )
cname = ORepHelpers::getShortName(conf->oind->getMapName(id)); cname = ORepHelpers::getShortName(conf->oind->getMapName(id));
...@@ -70,7 +73,7 @@ SharedMemory::SharedMemory( ObjectId id, string datafile, std::string confname ) ...@@ -70,7 +73,7 @@ SharedMemory::SharedMemory( ObjectId id, string datafile, std::string confname )
string t_field = conf->getArgParam("--t-filter-field"); string t_field = conf->getArgParam("--t-filter-field");
string t_fvalue = conf->getArgParam("--t-filter-value"); string t_fvalue = conf->getArgParam("--t-filter-value");
int lock_msec = conf->getArgPInt("--lock-value-pause",0); int lock_msec = conf->getArgPInt("--lock-rvalue-pause-msec",5);
if( lock_msec < 0 ) if( lock_msec < 0 )
lock_msec = 0; lock_msec = 0;
setCheckLockValuePause(lock_msec); setCheckLockValuePause(lock_msec);
...@@ -269,7 +272,7 @@ void SharedMemory::sysCommand( SystemMessage *sm ) ...@@ -269,7 +272,7 @@ void SharedMemory::sysCommand( SystemMessage *sm )
// подождать пока пройдёт инициализация // подождать пока пройдёт инициализация
// см. activateObject() // см. activateObject()
UniSetTypes::uniset_mutex_lock l(mutex_start, 10000); UniSetTypes::uniset_rwmutex_rlock l(mutex_start);
askTimer(tmHeartBeatCheck,heartbeatCheckTime); askTimer(tmHeartBeatCheck,heartbeatCheckTime);
askTimer(tmEvent,evntPause,1); askTimer(tmEvent,evntPause,1);
...@@ -328,11 +331,11 @@ bool SharedMemory::activateObject() ...@@ -328,11 +331,11 @@ bool SharedMemory::activateObject()
// см. sysCommand() // см. sysCommand()
{ {
{ {
uniset_mutex_lock l(act_mutex,100); uniset_rwmutex_wrlock l(mutex_act);
activated = false; activated = false;
} }
UniSetTypes::uniset_mutex_lock l(mutex_start, 5000); UniSetTypes::uniset_rwmutex_wrlock l(mutex_start);
res = IONotifyController_LT::activateObject(); res = IONotifyController_LT::activateObject();
// инициализируем указатели // инициализируем указатели
...@@ -356,7 +359,7 @@ bool SharedMemory::activateObject() ...@@ -356,7 +359,7 @@ bool SharedMemory::activateObject()
} }
{ {
uniset_mutex_lock l(act_mutex,100); uniset_rwmutex_wrlock l(mutex_act);
activated = true; activated = true;
} }
} }
...@@ -864,7 +867,7 @@ std::ostream& operator<<( std::ostream& os, const SharedMemory::HistoryInfo& h ) ...@@ -864,7 +867,7 @@ std::ostream& operator<<( std::ostream& os, const SharedMemory::HistoryInfo& h )
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool SharedMemory::isActivated() bool SharedMemory::isActivated()
{ {
uniset_mutex_lock l(act_mutex,300); uniset_rwmutex_rlock l(mutex_act);
return activated; return activated;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -350,7 +350,7 @@ class SharedMemory: ...@@ -350,7 +350,7 @@ class SharedMemory:
void buildEventList( xmlNode* cnode ); void buildEventList( xmlNode* cnode );
void readEventList( std::string oname ); void readEventList( std::string oname );
UniSetTypes::uniset_mutex mutex_start; UniSetTypes::uniset_rwmutex mutex_start;
struct HeartBeatInfo struct HeartBeatInfo
{ {
...@@ -422,8 +422,8 @@ class SharedMemory: ...@@ -422,8 +422,8 @@ class SharedMemory:
IOController_i::SensorInfo siPulsar; IOController_i::SensorInfo siPulsar;
UniversalIO::IOTypes iotypePulsar; UniversalIO::IOTypes iotypePulsar;
int msecPulsar; int msecPulsar;
UniSetTypes::uniset_mutex act_mutex; UniSetTypes::uniset_rwmutex mutex_act;
private: private:
HistorySlot m_historySignal; HistorySlot m_historySignal;
......
...@@ -532,7 +532,7 @@ void UNetExchange::sysCommand( UniSetTypes::SystemMessage *sm ) ...@@ -532,7 +532,7 @@ void UNetExchange::sysCommand( UniSetTypes::SystemMessage *sm )
dlog[Debug::CRIT] << myname << "(sysCommand): ************* don`t activate?! ************" << endl; dlog[Debug::CRIT] << myname << "(sysCommand): ************* don`t activate?! ************" << endl;
{ {
UniSetTypes::uniset_mutex_lock l(mutex_start, 10000); UniSetTypes::uniset_rwmutex_rlock l(mutex_start);
if( shm->isLocalwork() ) if( shm->isLocalwork() )
askSensors(UniversalIO::UIONotify); askSensors(UniversalIO::UIONotify);
} }
...@@ -625,7 +625,7 @@ bool UNetExchange::activateObject() ...@@ -625,7 +625,7 @@ bool UNetExchange::activateObject()
// см. sysCommand() // см. sysCommand()
{ {
activated = false; activated = false;
UniSetTypes::uniset_mutex_lock l(mutex_start, 5000); UniSetTypes::uniset_rwmutex_wrlock l(mutex_start);
UniSetObject_LT::activateObject(); UniSetObject_LT::activateObject();
initIterators(); initIterators();
activated = true; activated = true;
......
...@@ -125,7 +125,7 @@ class UNetExchange: ...@@ -125,7 +125,7 @@ class UNetExchange:
private: private:
UNetExchange(); UNetExchange();
bool initPause; bool initPause;
UniSetTypes::uniset_mutex mutex_start; UniSetTypes::uniset_rwmutex mutex_start;
PassiveTimer ptHeartBeat; PassiveTimer ptHeartBeat;
UniSetTypes::ObjectId sidHeartBeat; UniSetTypes::ObjectId sidHeartBeat;
......
...@@ -91,6 +91,7 @@ UNetReceiver::~UNetReceiver() ...@@ -91,6 +91,7 @@ UNetReceiver::~UNetReceiver()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetReceiver::setReceiveTimeout( timeout_t msec ) void UNetReceiver::setReceiveTimeout( timeout_t msec )
{ {
uniset_rwmutex_wrlock l(tmMutex);
recvTimeout = msec; recvTimeout = msec;
ptRecvTimeout.setTiming(msec); ptRecvTimeout.setTiming(msec);
} }
...@@ -141,18 +142,18 @@ void UNetReceiver::setLostPacketsID( UniSetTypes::ObjectId id ) ...@@ -141,18 +142,18 @@ void UNetReceiver::setLostPacketsID( UniSetTypes::ObjectId id )
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetReceiver::setLockUpdate( bool st ) void UNetReceiver::setLockUpdate( bool st )
{ {
uniset_mutex_lock l(lockMutex,200); uniset_rwmutex_wrlock l(lockMutex);
lockUpdate = st; lockUpdate = st;
if( !st ) if( !st )
ptPrepare.reset(); ptPrepare.reset();
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetReceiver::resetTimeout() void UNetReceiver::resetTimeout()
{ {
uniset_mutex_lock l(tmMutex,200); uniset_rwmutex_wrlock l(tmMutex);
ptRecvTimeout.reset(); ptRecvTimeout.reset();
trTimeout.change(false); trTimeout.change(false);
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetReceiver::start() void UNetReceiver::start()
...@@ -223,7 +224,7 @@ void UNetReceiver::real_update() ...@@ -223,7 +224,7 @@ void UNetReceiver::real_update()
while( k>0 ) while( k>0 )
{ {
{ // lock qpack { // lock qpack
uniset_mutex_lock l(packMutex); uniset_rwmutex_wrlock l(packMutex);
if( qpack.empty() ) if( qpack.empty() )
return; return;
...@@ -293,7 +294,7 @@ void UNetReceiver::real_update() ...@@ -293,7 +294,7 @@ void UNetReceiver::real_update()
// обновление данных в SM (блокировано) // обновление данных в SM (блокировано)
{ {
uniset_mutex_lock l(lockMutex,100); uniset_rwmutex_rlock l(lockMutex);
if( lockUpdate ) if( lockUpdate )
continue; continue;
} }
...@@ -336,7 +337,7 @@ void UNetReceiver::real_update() ...@@ -336,7 +337,7 @@ void UNetReceiver::real_update()
// обновление данных в SM (блокировано) // обновление данных в SM (блокировано)
{ {
uniset_mutex_lock l(lockMutex,100); uniset_rwmutex_rlock l(lockMutex);
if( lockUpdate ) if( lockUpdate )
continue; continue;
} }
...@@ -375,8 +376,14 @@ void UNetReceiver::stop() ...@@ -375,8 +376,14 @@ void UNetReceiver::stop()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetReceiver::receive() void UNetReceiver::receive()
{ {
dlog[Debug::INFO] << myname << ": ******************* receive start" << endl; if( dlog.debugging(Debug::INFO) )
ptRecvTimeout.setTiming(recvTimeout); dlog[Debug::INFO] << myname << ": ******************* receive start" << endl;
{
uniset_rwmutex_wrlock l(tmMutex);
ptRecvTimeout.setTiming(recvTimeout);
}
bool tout = false; bool tout = false;
while( activated ) while( activated )
{ {
...@@ -384,27 +391,30 @@ void UNetReceiver::receive() ...@@ -384,27 +391,30 @@ void UNetReceiver::receive()
{ {
if( recv() ) if( recv() )
{ {
uniset_mutex_lock l(tmMutex,100); uniset_rwmutex_wrlock l(tmMutex);
ptRecvTimeout.reset(); ptRecvTimeout.reset();
} }
} }
catch( UniSetTypes::Exception& ex) catch( UniSetTypes::Exception& ex)
{ {
dlog[Debug::WARN] << myname << "(receive): " << ex << std::endl; if( dlog.debugging(Debug::WARN) )
dlog[Debug::WARN] << myname << "(receive): " << ex << std::endl;
} }
catch( std::exception& e ) catch( std::exception& e )
{ {
dlog[Debug::WARN] << myname << "(receive): " << e.what()<< std::endl; if( dlog.debugging(Debug::WARN) )
dlog[Debug::WARN] << myname << "(receive): " << e.what()<< std::endl;
} }
catch(...) catch(...)
{ {
dlog[Debug::WARN] << myname << "(receive): catch ..." << std::endl; if( dlog.debugging(Debug::WARN) )
} dlog[Debug::WARN] << myname << "(receive): catch ..." << std::endl;
}
// делаем через промежуточную переменную // делаем через промежуточную переменную
// чтобы поскорее освободить mutex // чтобы поскорее освободить mutex
{ {
uniset_mutex_lock l(tmMutex,100); uniset_rwmutex_rlock l(tmMutex);
tout = ptRecvTimeout.checkTime(); tout = ptRecvTimeout.checkTime();
} }
...@@ -420,7 +430,8 @@ void UNetReceiver::receive() ...@@ -420,7 +430,8 @@ void UNetReceiver::receive()
msleep(recvpause); msleep(recvpause);
} }
dlog[Debug::INFO] << myname << ": ************* receive FINISH **********" << endl; if( dlog.debugging(Debug::INFO) )
dlog[Debug::INFO] << myname << ": ************* receive FINISH **********" << endl;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
bool UNetReceiver::recv() bool UNetReceiver::recv()
...@@ -471,7 +482,7 @@ bool UNetReceiver::recv() ...@@ -471,7 +482,7 @@ bool UNetReceiver::recv()
#endif #endif
{ // lock qpack { // lock qpack
uniset_mutex_lock l(packMutex,2000); uniset_rwmutex_wrlock l(packMutex);
if( !waitClean ) if( !waitClean )
{ {
qpack.push(pack); qpack.push(pack);
......
...@@ -115,7 +115,7 @@ class UNetReceiver ...@@ -115,7 +115,7 @@ class UNetReceiver
ost::tpport_t port; ost::tpport_t port;
std::string myname; std::string myname;
UniSetTypes::uniset_mutex pollMutex; UniSetTypes::uniset_rwmutex pollMutex;
PassiveTimer ptRecvTimeout; PassiveTimer ptRecvTimeout;
PassiveTimer ptPrepare; PassiveTimer ptPrepare;
timeout_t recvTimeout; timeout_t recvTimeout;
...@@ -147,7 +147,7 @@ class UNetReceiver ...@@ -147,7 +147,7 @@ class UNetReceiver
PacketQueue qpack; /*!< очередь принятых пакетов (отсортированных по возрастанию номера пакета) */ PacketQueue qpack; /*!< очередь принятых пакетов (отсортированных по возрастанию номера пакета) */
UniSetUDP::UDPMessage pack; /*!< просто буфер для получения очередного сообщения */ UniSetUDP::UDPMessage pack; /*!< просто буфер для получения очередного сообщения */
UniSetUDP::UDPPacket r_buf; UniSetUDP::UDPPacket r_buf;
UniSetTypes::uniset_mutex packMutex; /*!< mutex для работы с очередью */ UniSetTypes::uniset_rwmutex packMutex; /*!< mutex для работы с очередью */
unsigned long pnum; /*!< текущий номер обработанного сообщения, для проверки непрерывности последовательности пакетов */ unsigned long pnum; /*!< текущий номер обработанного сообщения, для проверки непрерывности последовательности пакетов */
/*! максимальная разница межд номерами пакетов, при которой считается, что счётчик пакетов /*! максимальная разница межд номерами пакетов, при которой считается, что счётчик пакетов
...@@ -162,11 +162,11 @@ class UNetReceiver ...@@ -162,11 +162,11 @@ class UNetReceiver
int maxProcessingCount; /*!< максимальное число обрабатываемых за один раз сообщений */ int maxProcessingCount; /*!< максимальное число обрабатываемых за один раз сообщений */
bool lockUpdate; /*!< флаг блокировки сохранения принятых данных в SM */ bool lockUpdate; /*!< флаг блокировки сохранения принятых данных в SM */
UniSetTypes::uniset_mutex lockMutex; UniSetTypes::uniset_rwmutex lockMutex;
EventSlot slEvent; EventSlot slEvent;
Trigger trTimeout; Trigger trTimeout;
UniSetTypes::uniset_mutex tmMutex; UniSetTypes::uniset_rwmutex tmMutex;
struct ItemInfo struct ItemInfo
{ {
......
...@@ -128,12 +128,12 @@ void UNetSender::updateItem( DMap::iterator& it, long value ) ...@@ -128,12 +128,12 @@ void UNetSender::updateItem( DMap::iterator& it, long value )
if( it->iotype == UniversalIO::DigitalInput || it->iotype == UniversalIO::DigitalOutput ) if( it->iotype == UniversalIO::DigitalInput || it->iotype == UniversalIO::DigitalOutput )
{ {
UniSetTypes::uniset_mutex_lock l(pack_mutex,100); UniSetTypes::uniset_rwmutex_wrlock l(pack_mutex);
mypack.setDData(it->pack_ind,value); mypack.setDData(it->pack_ind,value);
} }
else if( it->iotype == UniversalIO::AnalogInput || it->iotype == UniversalIO::AnalogOutput ) else if( it->iotype == UniversalIO::AnalogInput || it->iotype == UniversalIO::AnalogOutput )
{ {
UniSetTypes::uniset_mutex_lock l(pack_mutex,100); UniSetTypes::uniset_rwmutex_wrlock l(pack_mutex);
mypack.setAData(it->pack_ind,value); mypack.setAData(it->pack_ind,value);
} }
} }
...@@ -190,7 +190,7 @@ void UNetSender::send() ...@@ -190,7 +190,7 @@ void UNetSender::send()
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void UNetSender::real_send() void UNetSender::real_send()
{ {
UniSetTypes::uniset_mutex_lock l(pack_mutex,300); UniSetTypes::uniset_rwmutex_rlock l(pack_mutex);
mypack.num = packetnum++; mypack.num = packetnum++;
if( packetnum > UniSetUDP::MaxPacketNum ) if( packetnum > UniSetUDP::MaxPacketNum )
...@@ -199,7 +199,6 @@ void UNetSender::real_send() ...@@ -199,7 +199,6 @@ void UNetSender::real_send()
if( !udp->isPending(ost::Socket::pendingOutput) ) if( !udp->isPending(ost::Socket::pendingOutput) )
return; return;
mypack.transport_msg(s_msg); mypack.transport_msg(s_msg);
size_t ret = udp->send( (char*)s_msg.data, s_msg.len ); size_t ret = udp->send( (char*)s_msg.data, s_msg.len );
if( ret < s_msg.len ) if( ret < s_msg.len )
......
...@@ -88,8 +88,8 @@ class UNetSender ...@@ -88,8 +88,8 @@ class UNetSender
std::string myname; std::string myname;
int sendpause; int sendpause;
bool activated; bool activated;
UniSetTypes::uniset_mutex pack_mutex; UniSetTypes::uniset_rwmutex pack_mutex;
UniSetUDP::UDPMessage mypack; UniSetUDP::UDPMessage mypack;
DMap dlist; DMap dlist;
int maxItem; int maxItem;
......
...@@ -257,7 +257,7 @@ IOController_i::ShortMapSeq* UniExchange::getSensors() ...@@ -257,7 +257,7 @@ IOController_i::ShortMapSeq* UniExchange::getSensors()
{ {
IOController_i::ShortMap m; IOController_i::ShortMap m;
{ {
uniset_spin_lock lock(it->val_lock,30); uniset_rwmutex_rlock lock(it->val_lock);
m.id = it->id; m.id = it->id;
m.value = it->val; m.value = it->val;
m.type = it->type; m.type = it->type;
...@@ -274,7 +274,7 @@ void UniExchange::updateLocalData() ...@@ -274,7 +274,7 @@ void UniExchange::updateLocalData()
{ {
try try
{ {
uniset_spin_lock lock(it->val_lock,30); uniset_rwmutex_wrlock lock(it->val_lock);
if( it->type == UniversalIO::DigitalInput || if( it->type == UniversalIO::DigitalInput ||
it->type == UniversalIO::DigitalOutput ) it->type == UniversalIO::DigitalOutput )
{ {
......
...@@ -78,7 +78,7 @@ class UniExchange: ...@@ -78,7 +78,7 @@ class UniExchange:
long val; long val;
long id; long id;
UniversalIO::IOTypes type; UniversalIO::IOTypes type;
UniSetTypes::uniset_spin_mutex val_lock; UniSetTypes::uniset_rwmutex val_lock;
}; };
typedef std::vector<SInfo> SList; typedef std::vector<SInfo> SList;
......
...@@ -106,7 +106,7 @@ static const int NoSafety = -1; ...@@ -106,7 +106,7 @@ static const int NoSafety = -1;
IOController::AIOStateList::iterator ait; IOController::AIOStateList::iterator ait;
IOController::DIOStateList::iterator dit; IOController::DIOStateList::iterator dit;
UniSetTypes::uniset_spin_mutex val_lock; /*!< блокировка на время "работы" со значением */ UniSetTypes::uniset_rwmutex val_lock; /*!< блокировка на время "работы" со значением */
friend std::ostream& operator<<(std::ostream& os, IOBase& inf ); friend std::ostream& operator<<(std::ostream& os, IOBase& inf );
......
...@@ -89,6 +89,7 @@ class SMInterface ...@@ -89,6 +89,7 @@ class SMInterface
CORBA::Object_var oref; CORBA::Object_var oref;
UniSetTypes::ObjectId shmID; UniSetTypes::ObjectId shmID;
UniSetTypes::ObjectId myid; UniSetTypes::ObjectId myid;
UniSetTypes::uniset_rwmutex shmMutex;
}; };
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
......
...@@ -121,7 +121,7 @@ void IOBase::processingAsAI( IOBase* it, long val, SMInterface* shm, bool force ...@@ -121,7 +121,7 @@ void IOBase::processingAsAI( IOBase* it, long val, SMInterface* shm, bool force
// проверка на обрыв // проверка на обрыв
if( it->check_channel_break(val) ) if( it->check_channel_break(val) )
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
it->value = ChannelBreakValue; it->value = ChannelBreakValue;
shm->localSetUndefinedState(it->ait,true,it->si.id); shm->localSetUndefinedState(it->ait,true,it->si.id);
return; return;
...@@ -170,7 +170,7 @@ void IOBase::processingAsAI( IOBase* it, long val, SMInterface* shm, bool force ...@@ -170,7 +170,7 @@ void IOBase::processingAsAI( IOBase* it, long val, SMInterface* shm, bool force
// если предыдущее значение "обрыв", // если предыдущее значение "обрыв",
// то сбрасываем признак // то сбрасываем признак
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
if( it->value == ChannelBreakValue ) if( it->value == ChannelBreakValue )
shm->localSetUndefinedState(it->ait,false,it->si.id); shm->localSetUndefinedState(it->ait,false,it->si.id);
...@@ -200,7 +200,7 @@ void IOBase::processingFasAI( IOBase* it, float fval, SMInterface* shm, bool for ...@@ -200,7 +200,7 @@ void IOBase::processingFasAI( IOBase* it, float fval, SMInterface* shm, bool for
// проверка на обрыв // проверка на обрыв
if( it->check_channel_break(val) ) if( it->check_channel_break(val) )
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
it->value = ChannelBreakValue; it->value = ChannelBreakValue;
shm->localSetUndefinedState(it->ait,true,it->si.id); shm->localSetUndefinedState(it->ait,true,it->si.id);
return; return;
...@@ -228,7 +228,7 @@ void IOBase::processingFasAI( IOBase* it, float fval, SMInterface* shm, bool for ...@@ -228,7 +228,7 @@ void IOBase::processingFasAI( IOBase* it, float fval, SMInterface* shm, bool for
// если предыдущее значение "обрыв", // если предыдущее значение "обрыв",
// то сбрасываем признак // то сбрасываем признак
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
if( it->value == ChannelBreakValue ) if( it->value == ChannelBreakValue )
shm->localSetUndefinedState(it->ait,false,it->si.id); shm->localSetUndefinedState(it->ait,false,it->si.id);
...@@ -262,7 +262,7 @@ void IOBase::processingAsDI( IOBase* it, bool set, SMInterface* shm, bool force ...@@ -262,7 +262,7 @@ void IOBase::processingAsDI( IOBase* it, bool set, SMInterface* shm, bool force
set = it->check_off_delay(set); // фильтр на отпускание set = it->check_off_delay(set); // фильтр на отпускание
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_wrlock lock(it->val_lock);
if( force || (bool)it->value!=set ) if( force || (bool)it->value!=set )
{ {
if( it->stype == UniversalIO::DigitalInput ) if( it->stype == UniversalIO::DigitalInput )
...@@ -281,7 +281,7 @@ void IOBase::processingAsDI( IOBase* it, bool set, SMInterface* shm, bool force ...@@ -281,7 +281,7 @@ void IOBase::processingAsDI( IOBase* it, bool set, SMInterface* shm, bool force
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
long IOBase::processingAsAO( IOBase* it, SMInterface* shm, bool force ) long IOBase::processingAsAO( IOBase* it, SMInterface* shm, bool force )
{ {
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_rlock lock(it->val_lock);
long val = it->value; long val = it->value;
// проверка зависимости // проверка зависимости
...@@ -338,7 +338,7 @@ bool IOBase::processingAsDO( IOBase* it, SMInterface* shm, bool force ) ...@@ -338,7 +338,7 @@ bool IOBase::processingAsDO( IOBase* it, SMInterface* shm, bool force )
if( !it->check_depend(shm) ) if( !it->check_depend(shm) )
return (bool)it->d_off_value; return (bool)it->d_off_value;
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_rlock lock(it->val_lock);
bool set = it->value; bool set = it->value;
if( force ) if( force )
...@@ -359,7 +359,7 @@ float IOBase::processingFasAO( IOBase* it, SMInterface* shm, bool force ) ...@@ -359,7 +359,7 @@ float IOBase::processingFasAO( IOBase* it, SMInterface* shm, bool force )
if( !it->check_depend(shm) ) if( !it->check_depend(shm) )
return (float)it->d_off_value; return (float)it->d_off_value;
uniset_spin_lock lock(it->val_lock); uniset_rwmutex_rlock lock(it->val_lock);
long val = it->value; long val = it->value;
if( force ) if( force )
......
...@@ -10,7 +10,7 @@ using namespace UniSetTypes; ...@@ -10,7 +10,7 @@ using namespace UniSetTypes;
#define BEG_FUNC(name) \ #define BEG_FUNC(name) \
try \ try \
{ \ { \
uniset_mutex_lock l(shmMutex,500); \ uniset_rwmutex_wrlock l(shmMutex); \
IONotifyController_i_var shm;\ IONotifyController_i_var shm;\
for( unsigned int i=0; i<conf->getRepeatCount(); i++)\ for( unsigned int i=0; i<conf->getRepeatCount(); i++)\
{\ {\
...@@ -33,7 +33,7 @@ using namespace UniSetTypes; ...@@ -33,7 +33,7 @@ using namespace UniSetTypes;
#define BEG_FUNC1(name) \ #define BEG_FUNC1(name) \
try \ try \
{ \ { \
uniset_mutex_lock l(shmMutex,500); \ uniset_rwmutex_wrlock l(shmMutex); \
if( true ) \ if( true ) \
{ \ { \
try \ try \
......
...@@ -164,7 +164,7 @@ class IOController: ...@@ -164,7 +164,7 @@ class IOController:
bool block_state; bool block_state;
bool db_ignore; /*!< не писать изменения в БД */ bool db_ignore; /*!< не писать изменения в БД */
UniSetTypes::uniset_spin_mutex val_lock; /*!< флаг блокирующий работу со значением */ UniSetTypes::uniset_rwmutex val_lock; /*!< флаг блокирующий работу со значением */
}; };
struct UniAnalogIOInfo: struct UniAnalogIOInfo:
...@@ -188,7 +188,7 @@ class IOController: ...@@ -188,7 +188,7 @@ class IOController:
long block_value; long block_value;
bool db_ignore; /*!< не писать изменения в БД */ bool db_ignore; /*!< не писать изменения в БД */
UniSetTypes::uniset_spin_mutex val_lock; /*!< флаг блокирующий работу со значением */ UniSetTypes::uniset_rwmutex val_lock; /*!< флаг блокирующий работу со значением */
}; };
...@@ -377,8 +377,8 @@ class IOController: ...@@ -377,8 +377,8 @@ class IOController:
DIOStateList dioList; /*!< список с текущим состоянием дискретных входов/выходов */ DIOStateList dioList; /*!< список с текущим состоянием дискретных входов/выходов */
AIOStateList aioList; /*!< список с текущим состоянием аналоговых входов/выходов */ AIOStateList aioList; /*!< список с текущим состоянием аналоговых входов/выходов */
UniSetTypes::uniset_mutex dioMutex; /*!< замок для блокирования совместного доступа к dioList */ UniSetTypes::uniset_rwmutex dioMutex; /*!< замок для блокирования совместного доступа к dioList */
UniSetTypes::uniset_mutex aioMutex; /*!< замок для блокирования совместного доступа к aioList */ UniSetTypes::uniset_rwmutex aioMutex; /*!< замок для блокирования совместного доступа к aioList */
bool isPingDBServer; // флаг связи с DBServer-ом bool isPingDBServer; // флаг связи с DBServer-ом
...@@ -389,7 +389,8 @@ class IOController: ...@@ -389,7 +389,8 @@ class IOController:
DependsSlot bslot; /*!< block depends slot */ DependsSlot bslot; /*!< block depends slot */
int checkLockValuePause; int checkLockValuePause;
UniSetTypes::uniset_mutex loggingMutex; /*!< logging info mutex */ UniSetTypes::uniset_rwmutex loggingMutex; /*!< logging info mutex */
}; };
// --------------------------------------------------------------------------
#endif #endif
// --------------------------------------------------------------------------
...@@ -278,7 +278,7 @@ class IONotifyController: ...@@ -278,7 +278,7 @@ class IONotifyController:
void onChangeUndefined( DependsList::iterator it, bool undefined ); void onChangeUndefined( DependsList::iterator it, bool undefined );
UniSetTypes::uniset_mutex sig_mutex; UniSetTypes::uniset_rwmutex sig_mutex;
ChangeSignal changeSignal; ChangeSignal changeSignal;
private: private:
...@@ -307,17 +307,18 @@ class IONotifyController: ...@@ -307,17 +307,18 @@ class IONotifyController:
AskMap askAOList; /*!< список потребителей по аналоговым выходам */ AskMap askAOList; /*!< список потребителей по аналоговым выходам */
/*! замок для блокирования совместного доступа к cписку потребителей дискретных датчиков */ /*! замок для блокирования совместного доступа к cписку потребителей дискретных датчиков */
UniSetTypes::uniset_mutex askDMutex; UniSetTypes::uniset_rwmutex askDMutex;
/*! замок для блокирования совместного доступа к cписку потребителей аналоговых датчиков */ /*! замок для блокирования совместного доступа к cписку потребителей аналоговых датчиков */
UniSetTypes::uniset_mutex askAMutex; UniSetTypes::uniset_rwmutex askAMutex;
/*! замок для блокирования совместного доступа к cписку потребителей пороговых датчиков */ /*! замок для блокирования совместного доступа к cписку потребителей пороговых датчиков */
UniSetTypes::uniset_mutex trshMutex; UniSetTypes::uniset_rwmutex trshMutex;
/*! замок для блокирования совместного доступа к cписку потребителей аналоговых выходов */ /*! замок для блокирования совместного доступа к cписку потребителей аналоговых выходов */
UniSetTypes::uniset_mutex askAOMutex; UniSetTypes::uniset_rwmutex askAOMutex;
/*! замок для блокирования совместного доступа к cписку потребителей дискретных выходов */ /*! замок для блокирования совместного доступа к cписку потребителей дискретных выходов */
UniSetTypes::uniset_mutex askDOMutex; UniSetTypes::uniset_rwmutex askDOMutex;
int maxAttemtps; /*! timeout for consumer */ int maxAttemtps; /*! timeout for consumer */
}; };
// --------------------------------------------------------------------------
#endif #endif
// --------------------------------------------------------------------------
...@@ -182,7 +182,7 @@ class LT_Object ...@@ -182,7 +182,7 @@ class LT_Object
private: private:
TimersList tlst; TimersList tlst;
/*! замок для блокирования совместного доступа к cписку таймеров */ /*! замок для блокирования совместного доступа к cписку таймеров */
UniSetTypes::uniset_mutex lstMutex; UniSetTypes::uniset_rwmutex lstMutex;
timeout_t sleepTime; /*!< текущее время ожидания */ timeout_t sleepTime; /*!< текущее время ожидания */
PassiveTimer tmLast; PassiveTimer tmLast;
}; };
......
...@@ -51,6 +51,7 @@ namespace UniSetTypes ...@@ -51,6 +51,7 @@ namespace UniSetTypes
void unlock(); void unlock();
inline std::string name(){ return nm; } inline std::string name(){ return nm; }
inline void setName( const std::string& name ){ nm = name; }
protected: protected:
...@@ -65,6 +66,8 @@ namespace UniSetTypes ...@@ -65,6 +66,8 @@ namespace UniSetTypes
mutex_atomic_t locked; mutex_atomic_t locked;
}; };
std::ostream& operator<<(std::ostream& os, uniset_mutex& m );
// -------------------------------------------------------------------------
/*! \class uniset_mutex_lock /*! \class uniset_mutex_lock
* \author Pavel Vainerman * \author Pavel Vainerman
* *
...@@ -90,11 +93,12 @@ namespace UniSetTypes ...@@ -90,11 +93,12 @@ namespace UniSetTypes
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Mutex c приоритетом WRlock над RLock... // Mutex c приоритетом WRlock над RLock...
class uniset_spin_mutex class uniset_rwmutex
{ {
public: public:
uniset_spin_mutex(); uniset_rwmutex( const std::string& name );
~uniset_spin_mutex(); uniset_rwmutex();
~uniset_rwmutex();
void lock( int check_pause_msec=1 ); void lock( int check_pause_msec=1 );
void unlock(); void unlock();
...@@ -102,54 +106,43 @@ namespace UniSetTypes ...@@ -102,54 +106,43 @@ namespace UniSetTypes
void wrlock( int check_pause_msec=1 ); void wrlock( int check_pause_msec=1 );
void rlock( int check_pause_msec=1 ); void rlock( int check_pause_msec=1 );
uniset_spin_mutex (const uniset_spin_mutex& r); uniset_rwmutex (const uniset_rwmutex& r);
const uniset_spin_mutex &operator=(const uniset_spin_mutex& r); const uniset_rwmutex &operator=(const uniset_rwmutex& r);
inline std::string name(){ return nm; }
inline void setName( const std::string& name ){ nm = name; }
private: private:
friend class uniset_spin_lock; std::string nm;
friend class uniset_rwmutex_lock;
ost::ThreadLock m; ost::ThreadLock m;
ost::AtomicCounter wr_wait; ost::AtomicCounter wr_wait;
}; };
std::ostream& operator<<(std::ostream& os, uniset_rwmutex& m );
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
class uniset_spin_lock class uniset_rwmutex_wrlock
{ {
public: public:
uniset_spin_lock( uniset_spin_mutex& m, int check_pause_msec ); uniset_rwmutex_wrlock( uniset_rwmutex& m, int check_pause_msec=1 );
~uniset_spin_lock(); ~uniset_rwmutex_wrlock();
protected:
uniset_spin_lock( uniset_spin_mutex& _m ): m(_m){}
uniset_spin_mutex& m;
private: private:
uniset_spin_lock(const uniset_spin_lock&); uniset_rwmutex_wrlock(const uniset_rwmutex_wrlock&);
uniset_spin_lock& operator=(const uniset_spin_lock&); uniset_rwmutex_wrlock& operator=(const uniset_rwmutex_wrlock&);
uniset_rwmutex& m;
}; };
class uniset_spin_wrlock: class uniset_rwmutex_rlock
protected uniset_spin_lock
{ {
public: public:
uniset_spin_wrlock( uniset_spin_mutex& m, int check_pause_msec=1 ); uniset_rwmutex_rlock( uniset_rwmutex& m, int check_pause_msec=5 );
~uniset_spin_wrlock(); ~uniset_rwmutex_rlock();
private: private:
uniset_spin_wrlock(const uniset_spin_wrlock&); uniset_rwmutex_rlock(const uniset_rwmutex_rlock&);
uniset_spin_wrlock& operator=(const uniset_spin_wrlock&); uniset_rwmutex_rlock& operator=(const uniset_rwmutex_rlock&);
uniset_rwmutex& m;
}; };
class uniset_spin_rlock:
protected uniset_spin_lock
{
public:
uniset_spin_rlock( uniset_spin_mutex& m, int check_pause_msec=5 );
~uniset_spin_rlock();
private:
uniset_spin_rlock(const uniset_spin_rlock&);
uniset_spin_rlock& operator=(const uniset_spin_rlock&);
};
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
} // end of UniSetTypes namespace } // end of UniSetTypes namespace
......
...@@ -59,7 +59,7 @@ class ObjectsManager: ...@@ -59,7 +59,7 @@ class ObjectsManager:
{ {
public: public:
ObjectsManager( UniSetTypes::ObjectId id); ObjectsManager( UniSetTypes::ObjectId id);
ObjectsManager( const std::string name, const std::string section ); ObjectsManager( const std::string& name, const std::string& section );
virtual ~ObjectsManager(); virtual ~ObjectsManager();
...@@ -153,9 +153,8 @@ class ObjectsManager: ...@@ -153,9 +153,8 @@ class ObjectsManager:
ObjectsManagerList mlist; ObjectsManagerList mlist;
ObjectsList olist; ObjectsList olist;
UniSetTypes::uniset_mutex olistMutex; UniSetTypes::uniset_rwmutex olistMutex;
UniSetTypes::uniset_mutex mlistMutex; UniSetTypes::uniset_rwmutex mlistMutex;
}; };
#endif #endif
/* This file is part of the UniSet project
* Copyright (c) 2002 Free Software Foundation, Inc.
* Copyright (c) 2002 Pavel Vainerman
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// --------------------------------------------------------------------------
/*! \file
* \brief Интефес для создания и управления потоками
* \author Anthony Korbin
*/
//----------------------------------------------------------------------------
#ifndef PosixThread_h_
#define PosixThread_h_
//----------------------------------------------------------------------------------------
#include <pthread.h>
#include <iostream>
#include <signal.h>
//----------------------------------------------------------------------------------------
/*! \class PosixThread */
class PosixThread
{
public:
PosixThread();
virtual ~PosixThread();
void start( void *args ); /*!< запуск */
void stop();
void thrkill( int signo ); /*!< послать сигнал signo */
enum TAttr{ SCOPE, DETACH, PRIORITY };
void setAttr( TAttr Attr, int state );
pthread_t getTID(){ return tid; }
void setPriority( int priority );
static void* funcp( void * test );
protected:
void reinit();
virtual void work() = 0; /*!< Функция выполняемая в потоке */
void readlock( pthread_rwlock_t *lock = &lockx );
void writelock( pthread_rwlock_t *lock = &lockx );
void lock( pthread_mutex_t *mute = &mutex );
void unlock( pthread_mutex_t *mute = &mutex );
void rwunlock( pthread_rwlock_t *lock = &lockx );
void wait( pthread_cond_t *cond = &condx, pthread_mutex_t *mute = &mutex );
void continueRun( pthread_cond_t *cond = &condx );
void continueRunAll( pthread_cond_t *cond = &condx );
private:
pthread_t tid;
pthread_attr_t *attrPtr;
static pthread_rwlock_t lockx;
static pthread_mutex_t mutex;
static pthread_cond_t condx;
static int countThreads;
};
//----------------------------------------------------------------------------------------
#endif // PosixThread_h_
//----------------------------------------------------------------------------------------
...@@ -65,7 +65,7 @@ class UniSetObject: ...@@ -65,7 +65,7 @@ class UniSetObject:
public POA_UniSetObject_i public POA_UniSetObject_i
{ {
public: public:
UniSetObject(const std::string name, const std::string section); UniSetObject(const std::string& name, const std::string& section);
UniSetObject(UniSetTypes::ObjectId id); UniSetObject(UniSetTypes::ObjectId id);
UniSetObject(); UniSetObject();
virtual ~UniSetObject(); virtual ~UniSetObject();
...@@ -84,7 +84,7 @@ class UniSetObject: ...@@ -84,7 +84,7 @@ class UniSetObject:
/*! получить ссылку (на себя) */ /*! получить ссылку (на себя) */
inline UniSetTypes::ObjectPtr getRef() inline UniSetTypes::ObjectPtr getRef()
{ {
UniSetTypes::uniset_mutex_lock lock(refmutex, 300); UniSetTypes::uniset_rwmutex_rlock lock(refmutex);
return (UniSetTypes::ObjectPtr)CORBA::Object::_duplicate(oref); return (UniSetTypes::ObjectPtr)CORBA::Object::_duplicate(oref);
} }
...@@ -179,13 +179,6 @@ class UniSetObject: ...@@ -179,13 +179,6 @@ class UniSetObject:
*/ */
virtual void cleanMsgQueue( MessagesQueue& q ); virtual void cleanMsgQueue( MessagesQueue& q );
void setRecvMutexTimeout( unsigned long msec );
inline unsigned long getRecvMutexTimeout(){ return recvMutexTimeout; }
void setPushMutexTimeout( unsigned long msec );
unsigned long getPushMutexTimeout(){ return pushMutexTimeout; }
bool isActive(); bool isActive();
void setActive( bool set ); void setActive( bool set );
...@@ -222,7 +215,7 @@ class UniSetObject: ...@@ -222,7 +215,7 @@ class UniSetObject:
pid_t msgpid; // pid потока обработки сообщений pid_t msgpid; // pid потока обработки сообщений
bool reg; bool reg;
bool active; bool active;
UniSetTypes::uniset_mutex act_mutex; UniSetTypes::uniset_rwmutex mutex_act;
bool threadcreate; bool threadcreate;
UniSetTimer* tmr; UniSetTimer* tmr;
UniSetTypes::ObjectId myid; UniSetTypes::ObjectId myid;
...@@ -233,17 +226,15 @@ class UniSetObject: ...@@ -233,17 +226,15 @@ class UniSetObject:
MessagesQueue queueMsg; MessagesQueue queueMsg;
/*! замок для блокирования совместного доступа к очереди */ /*! замок для блокирования совместного доступа к очереди */
UniSetTypes::uniset_mutex qmutex; UniSetTypes::uniset_rwmutex qmutex;
/*! замок для блокирования совместного доступа к очереди */ /*! замок для блокирования совместного доступа к очереди */
UniSetTypes::uniset_mutex refmutex; UniSetTypes::uniset_rwmutex refmutex;
/*! размер очереди сообщений (при превышении происходит очистка) */ /*! размер очереди сообщений (при превышении происходит очистка) */
unsigned int SizeOfMessageQueue; unsigned int SizeOfMessageQueue;
/*! сколько сообщений удалять при очисте*/ /*! сколько сообщений удалять при очисте*/
unsigned int MaxCountRemoveOfMessage; unsigned int MaxCountRemoveOfMessage;
unsigned long recvMutexTimeout; /*!< таймаут на ожидание освобождения mutex-а при receiveMessage */
unsigned long pushMutexTimeout; /*!< таймаут на ожидание освобождения mutex-а при pushMessage */
// статистическая информация // статистическая информация
unsigned long stMaxQueueMessages; /*<! Максимальное число сообщений хранившихся в очереди */ unsigned long stMaxQueueMessages; /*<! Максимальное число сообщений хранившихся в очереди */
......
...@@ -146,9 +146,6 @@ namespace UniSetTypes ...@@ -146,9 +146,6 @@ namespace UniSetTypes
/*! Запрещенные для использования в именах объектов символы */ /*! Запрещенные для использования в именах объектов символы */
const char BadSymbols[]={'.','/'}; const char BadSymbols[]={'.','/'};
class uniset_mutex;
class uniset_mutex_lock;
/// Преобразование строки в число (воспринимает префикс 0, как 8-ное, префикс 0x, как 16-ное, минус для отриц. чисел) /// Преобразование строки в число (воспринимает префикс 0, как 8-ное, префикс 0x, как 16-ное, минус для отриц. чисел)
inline int uni_atoi( const char* str ) inline int uni_atoi( const char* str )
{ {
......
...@@ -324,7 +324,7 @@ class UniversalInterface ...@@ -324,7 +324,7 @@ class UniversalInterface
bool clean(); /*!< функция очистки кэш-а от старых ссылок */ bool clean(); /*!< функция очистки кэш-а от старых ссылок */
inline void clear() /*!< удаление всей информации */ inline void clear() /*!< удаление всей информации */
{ {
UniSetTypes::uniset_mutex_lock l(cmutex,200); UniSetTypes::uniset_rwmutex_wrlock l(cmutex);
mcache.clear(); mcache.clear();
}; };
...@@ -355,7 +355,7 @@ class UniversalInterface ...@@ -355,7 +355,7 @@ class UniversalInterface
typedef std::map<int, Info> CacheMap; typedef std::map<int, Info> CacheMap;
CacheMap mcache; CacheMap mcache;
UniSetTypes::uniset_mutex cmutex; UniSetTypes::uniset_rwmutex cmutex;
unsigned int MaxSize; /*!< максимальный размер кэша */ unsigned int MaxSize; /*!< максимальный размер кэша */
unsigned int CleanTime; /*!< период устаревания ссылок [мин] */ unsigned int CleanTime; /*!< период устаревания ссылок [мин] */
......
...@@ -193,7 +193,7 @@ class ModbusClient ...@@ -193,7 +193,7 @@ class ModbusClient
bool crcNoCheckit; bool crcNoCheckit;
UniSetTypes::uniset_mutex sendMutex; UniSetTypes::uniset_rwmutex sendMutex;
DebugStream dlog; DebugStream dlog;
void printProcessingTime(); void printProcessingTime();
......
...@@ -23,12 +23,12 @@ class ModbusRTUSlave: ...@@ -23,12 +23,12 @@ class ModbusRTUSlave:
public ModbusServer public ModbusServer
{ {
public: public:
ModbusRTUSlave( const std::string dev, bool use485=false, bool tr_ctl=false ); ModbusRTUSlave( const std::string& dev, bool use485=false, bool tr_ctl=false );
ModbusRTUSlave( ComPort* com ); ModbusRTUSlave( ComPort* com );
virtual ~ModbusRTUSlave(); virtual ~ModbusRTUSlave();
void setSpeed( ComPort::Speed s ); void setSpeed( ComPort::Speed s );
void setSpeed( const std::string s ); void setSpeed( const std::string& s );
ComPort::Speed getSpeed(); ComPort::Speed getSpeed();
virtual ModbusRTU::mbErrCode receive( ModbusRTU::ModbusAddr addr, timeout_t msecTimeout ); virtual ModbusRTU::mbErrCode receive( ModbusRTU::ModbusAddr addr, timeout_t msecTimeout );
......
...@@ -26,7 +26,7 @@ class TCPCheck ...@@ -26,7 +26,7 @@ class TCPCheck
void check_thread(); void check_thread();
inline void setResult( bool res ) inline void setResult( bool res )
{ {
UniSetTypes::uniset_mutex_lock l(m,50); UniSetTypes::uniset_rwmutex_wrlock l(m);
result = res; result = res;
} }
...@@ -34,7 +34,7 @@ class TCPCheck ...@@ -34,7 +34,7 @@ class TCPCheck
{ {
bool res = false; bool res = false;
{ {
UniSetTypes::uniset_mutex_lock l(m,50); UniSetTypes::uniset_rwmutex_rlock l(m);
res = result; res = result;
} }
return res; return res;
...@@ -43,7 +43,7 @@ class TCPCheck ...@@ -43,7 +43,7 @@ class TCPCheck
bool result; bool result;
std::string iaddr; std::string iaddr;
int tout_msec; int tout_msec;
UniSetTypes::uniset_mutex m; UniSetTypes::uniset_rwmutex m;
}; };
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#endif // _TCPCheck_H_ #endif // _TCPCheck_H_
......
...@@ -14,7 +14,8 @@ ModbusClient::ModbusClient(): ...@@ -14,7 +14,8 @@ ModbusClient::ModbusClient():
replyTimeOut_ms(2000), replyTimeOut_ms(2000),
aftersend_msec(0), aftersend_msec(0),
sleepPause_usec(100), sleepPause_usec(100),
crcNoCheckit(false) crcNoCheckit(false),
sendMutex("ModbusClient_sendMutex")
{ {
tmProcessing.setTiming(replyTimeOut_ms); tmProcessing.setTiming(replyTimeOut_ms);
} }
......
...@@ -11,10 +11,12 @@ using namespace std; ...@@ -11,10 +11,12 @@ using namespace std;
using namespace ModbusRTU; using namespace ModbusRTU;
using namespace UniSetTypes; using namespace UniSetTypes;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusRTUSlave::ModbusRTUSlave( const string dev, bool use485, bool tr_ctl ): ModbusRTUSlave::ModbusRTUSlave( const string& dev, bool use485, bool tr_ctl ):
port(NULL), port(NULL),
myport(true) myport(true)
{ {
recvMutex.setName("(ModbusRTUSlave): dev='" + dev + "' recvMutex:");
if( use485 ) if( use485 )
{ {
ComPort485F* cp; ComPort485F* cp;
...@@ -63,6 +65,13 @@ ModbusRTUSlave::~ModbusRTUSlave() ...@@ -63,6 +65,13 @@ ModbusRTUSlave::~ModbusRTUSlave()
mbErrCode ModbusRTUSlave::receive( ModbusRTU::ModbusAddr addr, timeout_t timeout ) mbErrCode ModbusRTUSlave::receive( ModbusRTU::ModbusAddr addr, timeout_t timeout )
{ {
uniset_mutex_lock lck(recvMutex,timeout); uniset_mutex_lock lck(recvMutex,timeout);
if( !lck.lock_ok() )
{
if( dlog.debugging(Debug::CRIT) )
dlog[Debug::CRIT] << "(ModbusRTUSlave::receive): Don`t lock " << recvMutex << endl;
return erTimeOut;
}
ModbusMessage buf; ModbusMessage buf;
mbErrCode res = erBadReplyNodeAddress; mbErrCode res = erBadReplyNodeAddress;
do do
...@@ -114,7 +123,7 @@ void ModbusRTUSlave::setSpeed( ComPort::Speed s ) ...@@ -114,7 +123,7 @@ void ModbusRTUSlave::setSpeed( ComPort::Speed s )
port->setSpeed(s); port->setSpeed(s);
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
void ModbusRTUSlave::setSpeed( const std::string s ) void ModbusRTUSlave::setSpeed( const std::string& s )
{ {
if( port != NULL ) if( port != NULL )
port->setSpeed(s); port->setSpeed(s);
......
...@@ -15,6 +15,7 @@ using namespace ModbusRTU; ...@@ -15,6 +15,7 @@ using namespace ModbusRTU;
using namespace UniSetTypes; using namespace UniSetTypes;
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
ModbusServer::ModbusServer(): ModbusServer::ModbusServer():
recvMutex("ModbusServer_recvMutex"),
recvTimeOut_ms(50), recvTimeOut_ms(50),
replyTimeout_ms(2000), replyTimeout_ms(2000),
aftersend_msec(0), aftersend_msec(0),
......
...@@ -2377,7 +2377,7 @@ IOController_i::ShortIOInfo UniversalInterface::getChangedTime( UniSetTypes::Obj ...@@ -2377,7 +2377,7 @@ IOController_i::ShortIOInfo UniversalInterface::getChangedTime( UniSetTypes::Obj
ObjectPtr UniversalInterface::CacheOfResolve::resolve( ObjectId id, ObjectId node ) ObjectPtr UniversalInterface::CacheOfResolve::resolve( ObjectId id, ObjectId node )
throw(NameNotFound) throw(NameNotFound)
{ {
UniSetTypes::uniset_mutex_lock l(cmutex,200); UniSetTypes::uniset_rwmutex_rlock l(cmutex);
//#warning Временно отключён кэш //#warning Временно отключён кэш
// throw UniSetTypes::NameNotFound(); // throw UniSetTypes::NameNotFound();
...@@ -2400,16 +2400,7 @@ ObjectPtr UniversalInterface::CacheOfResolve::resolve( ObjectId id, ObjectId nod ...@@ -2400,16 +2400,7 @@ ObjectPtr UniversalInterface::CacheOfResolve::resolve( ObjectId id, ObjectId nod
// ------------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------------
void UniversalInterface::CacheOfResolve::cache( ObjectId id, ObjectId node, ObjectVar ptr ) void UniversalInterface::CacheOfResolve::cache( ObjectId id, ObjectId node, ObjectVar ptr )
{ {
UniSetTypes::uniset_mutex_lock l(cmutex,220); UniSetTypes::uniset_rwmutex_wrlock l(cmutex);
//#warning Временно отключён кэш
// return;
// if( mcache.size() > MaxSize )
// {
// if( !clean() )
// unideb[Debug::CRIT] << "UI(resolve cache): не удалось уменьшить размер кэш-а!!!!"<< endl;
// }
UniSetTypes::KeyType k(key(id,node)); UniSetTypes::KeyType k(key(id,node));
CacheMap::iterator it = mcache.find(k); CacheMap::iterator it = mcache.find(k);
...@@ -2424,13 +2415,12 @@ void UniversalInterface::CacheOfResolve::cache( ObjectId id, ObjectId node, Obje ...@@ -2424,13 +2415,12 @@ void UniversalInterface::CacheOfResolve::cache( ObjectId id, ObjectId node, Obje
// ------------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------------
bool UniversalInterface::CacheOfResolve::clean() bool UniversalInterface::CacheOfResolve::clean()
{ {
UniSetTypes::uniset_mutex_lock l(cmutex,180); UniSetTypes::uniset_rwmutex_wrlock l(cmutex);
// return true;
if( unideb.debugging(Debug::INFO) ) if( unideb.debugging(Debug::INFO) )
unideb[Debug::INFO] << "UI: clean cache...."<< endl; unideb[Debug::INFO] << "UI: clean cache...."<< endl;
time_t tm = time(NULL)-CleanTime*60; time_t tm = time(NULL)-CleanTime*60;
// remove_if(mcache.begin(), mcache.end(),OldRef_eq(tm)); // remove_if(mcache.begin(), mcache.end(),OldRef_eq(tm));
for( CacheMap::iterator it=mcache.begin(); it!=mcache.end();) for( CacheMap::iterator it=mcache.begin(); it!=mcache.end();)
{ {
...@@ -2449,7 +2439,7 @@ bool UniversalInterface::CacheOfResolve::clean() ...@@ -2449,7 +2439,7 @@ bool UniversalInterface::CacheOfResolve::clean()
void UniversalInterface::CacheOfResolve::erase( UniSetTypes::ObjectId id, UniSetTypes::ObjectId node ) void UniversalInterface::CacheOfResolve::erase( UniSetTypes::ObjectId id, UniSetTypes::ObjectId node )
{ {
UniSetTypes::uniset_mutex_lock l(cmutex,220); UniSetTypes::uniset_rwmutex_wrlock l(cmutex);
//#warning Временно отключён кэш //#warning Временно отключён кэш
// return; // return;
......
...@@ -270,22 +270,28 @@ void ObjectsActivator::work() ...@@ -270,22 +270,28 @@ void ObjectsActivator::work()
} }
catch(CORBA::SystemException& ex) catch(CORBA::SystemException& ex)
{ {
unideb[Debug::CRIT] << myname << "(work): поймали CORBA::SystemException: " << ex.NP_minorString() << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(work): поймали CORBA::SystemException: " << ex.NP_minorString() << endl;
} }
catch(CORBA::Exception& ex) catch(CORBA::Exception& ex)
{ {
unideb[Debug::CRIT] << myname << "(work): поймали CORBA::Exception." << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(work): поймали CORBA::Exception." << endl;
} }
catch(omniORB::fatalException& fe) catch(omniORB::fatalException& fe)
{ {
unideb[Debug::CRIT] << myname << "(work): : поймали omniORB::fatalException:" << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(work): file: " << fe.file() << endl; {
unideb[Debug::CRIT] << myname << "(work): line: " << fe.line() << endl; unideb[Debug::CRIT] << myname << "(work): : поймали omniORB::fatalException:" << endl;
unideb[Debug::CRIT] << myname << "(work): mesg: " << fe.errmsg() << endl; unideb[Debug::CRIT] << myname << "(work): file: " << fe.file() << endl;
unideb[Debug::CRIT] << myname << "(work): line: " << fe.line() << endl;
unideb[Debug::CRIT] << myname << "(work): mesg: " << fe.errmsg() << endl;
}
} }
catch(...) catch(...)
{ {
unideb[Debug::CRIT] << myname << "(work): catch ..." << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(work): catch ..." << endl;
} }
if( unideb.debugging(Debug::SYSTEM) ) if( unideb.debugging(Debug::SYSTEM) )
......
...@@ -80,22 +80,29 @@ class OPush: public unary_function<UniSetObject*, bool> ...@@ -80,22 +80,29 @@ class OPush: public unary_function<UniSetObject*, bool>
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
ObjectsManager::ObjectsManager(): ObjectsManager::ObjectsManager():
UniSetObject(UniSetTypes::DefaultObjectId) UniSetObject(UniSetTypes::DefaultObjectId),
sig(0),
olistMutex("olistMutex"),
mlistMutex("mlistMutex")
{ {
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
ObjectsManager::ObjectsManager( ObjectId id): ObjectsManager::ObjectsManager( ObjectId id ):
UniSetObject(id), UniSetObject(id),
sig(0) sig(0)
{ {
olistMutex.setName(myname + "_olistMutex");
mlistMutex.setName(myname + "_mlistMutex");
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
ObjectsManager::ObjectsManager(const string name, const string section): ObjectsManager::ObjectsManager(const string& name, const string& section):
UniSetObject(name, section), UniSetObject(name, section),
sig(0) sig(0)
{ {
olistMutex.setName(myname + "_olistMutex");
mlistMutex.setName(myname + "_mlistMutex");
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
...@@ -141,7 +148,7 @@ void ObjectsManager::initPOA( ObjectsManager* rmngr ) ...@@ -141,7 +148,7 @@ void ObjectsManager::initPOA( ObjectsManager* rmngr )
bool ObjectsManager::addObject( UniSetObject *obj ) bool ObjectsManager::addObject( UniSetObject *obj )
{ {
{ //lock { //lock
uniset_mutex_lock lock(olistMutex, 1000); uniset_rwmutex_wrlock lock(olistMutex);
ObjectsList::iterator li=find(olist.begin(),olist.end(), obj); ObjectsList::iterator li=find(olist.begin(),olist.end(), obj);
if( li==olist.end() ) if( li==olist.end() )
{ {
...@@ -157,7 +164,7 @@ bool ObjectsManager::addObject( UniSetObject *obj ) ...@@ -157,7 +164,7 @@ bool ObjectsManager::addObject( UniSetObject *obj )
bool ObjectsManager::removeObject(UniSetObject* obj) bool ObjectsManager::removeObject(UniSetObject* obj)
{ {
{ //lock { //lock
uniset_mutex_lock lock(olistMutex, 1000); uniset_rwmutex_wrlock lock(olistMutex);
ObjectsList::iterator li=find(olist.begin(),olist.end(), obj); ObjectsList::iterator li=find(olist.begin(),olist.end(), obj);
if( li!=olist.end() ) if( li!=olist.end() )
{ {
...@@ -193,7 +200,7 @@ bool ObjectsManager::removeObject(UniSetObject* obj) ...@@ -193,7 +200,7 @@ bool ObjectsManager::removeObject(UniSetObject* obj)
} // unlock } // unlock
return true; return true;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
/*! /*!
...@@ -201,10 +208,11 @@ bool ObjectsManager::removeObject(UniSetObject* obj) ...@@ -201,10 +208,11 @@ bool ObjectsManager::removeObject(UniSetObject* obj)
*/ */
void ObjectsManager::managers(OManagerCommand cmd) void ObjectsManager::managers(OManagerCommand cmd)
{ {
unideb[Debug::INFO] << myname <<"(managers): mlist.size=" if( unideb.debugging(Debug::INFO) )
unideb[Debug::INFO] << myname <<"(managers): mlist.size="
<< mlist.size() << " cmd=" << cmd << endl; << mlist.size() << " cmd=" << cmd << endl;
{ //lock { //lock
uniset_mutex_lock lock(mlistMutex, 1000); uniset_rwmutex_rlock lock(mlistMutex);
for( ObjectsManagerList::iterator li=mlist.begin();li!=mlist.end();++li ) for( ObjectsManagerList::iterator li=mlist.begin();li!=mlist.end();++li )
{ {
try try
...@@ -233,23 +241,31 @@ void ObjectsManager::managers(OManagerCommand cmd) ...@@ -233,23 +241,31 @@ void ObjectsManager::managers(OManagerCommand cmd)
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
unideb[Debug::CRIT] << myname << "(managers): " << ex << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(managers): не смог зарегистрировать (разрегистрировать) объект -->"<< (*li)->getName() << endl; {
unideb[Debug::CRIT] << myname << "(managers): " << ex << endl;
unideb[Debug::CRIT] << myname << "(managers): не смог зарегистрировать (разрегистрировать) объект -->"<< (*li)->getName() << endl;
}
} }
catch(CORBA::SystemException& ex) catch(CORBA::SystemException& ex)
{ {
unideb[Debug::CRIT] << myname << "(managers): поймали CORBA::SystemException:" << ex.NP_minorString() << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(managers): поймали CORBA::SystemException:" << ex.NP_minorString() << endl;
} }
catch( CORBA::Exception& ex ) catch( CORBA::Exception& ex )
{ {
unideb[Debug::CRIT] << myname << "(managers): Caught CORBA::Exception. " << ex._name() << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(managers): Caught CORBA::Exception. " << ex._name() << endl;
} }
catch( omniORB::fatalException& fe ) catch( omniORB::fatalException& fe )
{ {
unideb[Debug::CRIT] << myname << "(managers): Caught omniORB::fatalException:" << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(managers): file: " << fe.file() {
<< " line: " << fe.line() unideb[Debug::CRIT] << myname << "(managers): Caught omniORB::fatalException:" << endl;
<< " mesg: " << fe.errmsg() << endl; unideb[Debug::CRIT] << myname << "(managers): file: " << fe.file()
<< " line: " << fe.line()
<< " mesg: " << fe.errmsg() << endl;
}
} }
} }
} // unlock } // unlock
...@@ -260,10 +276,11 @@ void ObjectsManager::managers(OManagerCommand cmd) ...@@ -260,10 +276,11 @@ void ObjectsManager::managers(OManagerCommand cmd)
*/ */
void ObjectsManager::objects(OManagerCommand cmd) void ObjectsManager::objects(OManagerCommand cmd)
{ {
unideb[Debug::INFO] << myname <<"(objects): olist.size=" if( unideb.debugging(Debug::INFO) )
unideb[Debug::INFO] << myname <<"(objects): olist.size="
<< olist.size() << " cmd=" << cmd << endl; << olist.size() << " cmd=" << cmd << endl;
{ //lock { //lock
uniset_mutex_lock lock(olistMutex, 1000); uniset_rwmutex_rlock lock(olistMutex);
for (ObjectsList::iterator li=olist.begin();li!=olist.end();++li) for (ObjectsList::iterator li=olist.begin();li!=olist.end();++li)
{ {
...@@ -293,25 +310,33 @@ void ObjectsManager::objects(OManagerCommand cmd) ...@@ -293,25 +310,33 @@ void ObjectsManager::objects(OManagerCommand cmd)
} }
catch( Exception& ex ) catch( Exception& ex )
{ {
unideb[Debug::CRIT] << myname << "(objects): " << ex << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(objects): не смог зарегистрировать (разрегистрировать) объект -->"<< (*li)->getName() << endl; {
unideb[Debug::CRIT] << myname << "(objects): " << ex << endl;
unideb[Debug::CRIT] << myname << "(objects): не смог зарегистрировать (разрегистрировать) объект -->"<< (*li)->getName() << endl;
}
} }
catch(CORBA::SystemException& ex) catch(CORBA::SystemException& ex)
{ {
unideb[Debug::CRIT] << myname << "(objects): поймали CORBA::SystemException:" << ex.NP_minorString() << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(objects): поймали CORBA::SystemException:" << ex.NP_minorString() << endl;
} }
catch( CORBA::Exception& ex ) catch( CORBA::Exception& ex )
{ {
unideb[Debug::CRIT] << myname << "(objects): Caught CORBA::Exception. " if( unideb.debugging(Debug::CRIT) )
<< ex._name() unideb[Debug::CRIT] << myname << "(objects): Caught CORBA::Exception. "
<< " (" << (*li)->getName() << ")" << endl; << ex._name()
<< " (" << (*li)->getName() << ")" << endl;
} }
catch( omniORB::fatalException& fe ) catch( omniORB::fatalException& fe )
{ {
unideb[Debug::CRIT] << myname << "(objects): Caught omniORB::fatalException:" << endl; if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(objects): file: " << fe.file() {
<< " line: " << fe.line() unideb[Debug::CRIT] << myname << "(objects): Caught omniORB::fatalException:" << endl;
<< " mesg: " << fe.errmsg() << endl; unideb[Debug::CRIT] << myname << "(objects): file: " << fe.file()
<< " line: " << fe.line()
<< " mesg: " << fe.errmsg() << endl;
}
} }
} }
} // unlock } // unlock
...@@ -362,13 +387,13 @@ void ObjectsManager::broadcast(const TransportMessage& msg) ...@@ -362,13 +387,13 @@ void ObjectsManager::broadcast(const TransportMessage& msg)
// Всем объектам... // Всем объектам...
{ //lock { //lock
uniset_mutex_lock lock(olistMutex, 2000); uniset_rwmutex_rlock lock(olistMutex);
for_each(olist.begin(),olist.end(),OPush(msg)); // STL метод for_each(olist.begin(),olist.end(),OPush(msg)); // STL метод
} // unlock } // unlock
// Всем менеджерам.... // Всем менеджерам....
{ //lock { //lock
uniset_mutex_lock lock(mlistMutex, 2000); uniset_rwmutex_rlock lock(mlistMutex);
for_each(mlist.begin(),mlist.end(),MPush(msg)); // STL метод for_each(mlist.begin(),mlist.end(),MPush(msg)); // STL метод
} // unlock } // unlock
} }
...@@ -377,7 +402,7 @@ void ObjectsManager::broadcast(const TransportMessage& msg) ...@@ -377,7 +402,7 @@ void ObjectsManager::broadcast(const TransportMessage& msg)
bool ObjectsManager::addManager( ObjectsManager *child ) bool ObjectsManager::addManager( ObjectsManager *child )
{ {
{ //lock { //lock
uniset_mutex_lock lock(mlistMutex, 1000); uniset_rwmutex_wrlock lock(mlistMutex);
// Проверка на совпадение // Проверка на совпадение
ObjectsManagerList::iterator it= find(mlist.begin(),mlist.end(),child); ObjectsManagerList::iterator it= find(mlist.begin(),mlist.end(),child);
...@@ -387,7 +412,7 @@ bool ObjectsManager::addManager( ObjectsManager *child ) ...@@ -387,7 +412,7 @@ bool ObjectsManager::addManager( ObjectsManager *child )
if( unideb.debugging(Debug::INFO) ) if( unideb.debugging(Debug::INFO) )
unideb[Debug::INFO] << myname << ": добавляем менеджер "<< child->getName()<< endl; unideb[Debug::INFO] << myname << ": добавляем менеджер "<< child->getName()<< endl;
} }
else else if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << myname << ": попытка повторного добавления объекта "<< child->getName() << endl; unideb[Debug::WARN] << myname << ": попытка повторного добавления объекта "<< child->getName() << endl;
} // unlock } // unlock
...@@ -398,7 +423,7 @@ bool ObjectsManager::addManager( ObjectsManager *child ) ...@@ -398,7 +423,7 @@ bool ObjectsManager::addManager( ObjectsManager *child )
bool ObjectsManager::removeManager( ObjectsManager* child ) bool ObjectsManager::removeManager( ObjectsManager* child )
{ {
{ //lock { //lock
uniset_mutex_lock lock(mlistMutex, 1000); uniset_rwmutex_wrlock lock(mlistMutex);
mlist.remove(child); mlist.remove(child);
} // unlock } // unlock
...@@ -411,7 +436,7 @@ const ObjectsManager* ObjectsManager::itemM(const ObjectId id) ...@@ -411,7 +436,7 @@ const ObjectsManager* ObjectsManager::itemM(const ObjectId id)
{ {
{ //lock { //lock
uniset_mutex_lock lock(mlistMutex, 1000); uniset_rwmutex_rlock lock(mlistMutex);
for( ObjectsManagerList::iterator li=mlist.begin(); li!=mlist.end();++li ) for( ObjectsManagerList::iterator li=mlist.begin(); li!=mlist.end();++li )
{ {
if ( (*li)->getId()==id ) if ( (*li)->getId()==id )
...@@ -427,7 +452,7 @@ const ObjectsManager* ObjectsManager::itemM(const ObjectId id) ...@@ -427,7 +452,7 @@ const ObjectsManager* ObjectsManager::itemM(const ObjectId id)
const UniSetObject* ObjectsManager::itemO(const ObjectId id) const UniSetObject* ObjectsManager::itemO(const ObjectId id)
{ {
{ //lock { //lock
uniset_mutex_lock lock(olistMutex, 1000); uniset_rwmutex_rlock lock(olistMutex);
for (ObjectsList::iterator li=olist.begin(); li!=olist.end();++li) for (ObjectsList::iterator li=olist.begin(); li!=olist.end();++li)
{ {
if ( (*li)->getId()==id ) if ( (*li)->getId()==id )
......
...@@ -101,7 +101,7 @@ stCountOfQueueFull(0) ...@@ -101,7 +101,7 @@ stCountOfQueueFull(0)
} }
UniSetObject::UniSetObject(const string name, const string section): UniSetObject::UniSetObject(const string& name, const string& section):
ui(UniSetTypes::DefaultObjectId), ui(UniSetTypes::DefaultObjectId),
mymngr(NULL), mymngr(NULL),
msgpid(0), msgpid(0),
...@@ -137,11 +137,18 @@ UniSetObject::~UniSetObject() ...@@ -137,11 +137,18 @@ UniSetObject::~UniSetObject()
disactivate(); disactivate();
delete tmr; delete tmr;
if(thr) if(thr)
{
thr->stop();
delete thr; delete thr;
}
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::init_object() void UniSetObject::init_object()
{ {
qmutex.setName(myname + "_qmutex");
refmutex.setName(myname + "_refmutex");
mutex_act.setName(myname + "_mutex_act");
SizeOfMessageQueue = conf->getArgPInt("--uniset-object-size-message-queue",conf->getField("SizeOfMessageQueue"), 1000); SizeOfMessageQueue = conf->getArgPInt("--uniset-object-size-message-queue",conf->getField("SizeOfMessageQueue"), 1000);
MaxCountRemoveOfMessage = conf->getArgInt("--uniset-object-maxcount-remove-message",conf->getField("MaxCountRemoveOfMessage")); MaxCountRemoveOfMessage = conf->getArgInt("--uniset-object-maxcount-remove-message",conf->getField("MaxCountRemoveOfMessage"));
...@@ -149,16 +156,11 @@ void UniSetObject::init_object() ...@@ -149,16 +156,11 @@ void UniSetObject::init_object()
MaxCountRemoveOfMessage = SizeOfMessageQueue / 4; MaxCountRemoveOfMessage = SizeOfMessageQueue / 4;
if( MaxCountRemoveOfMessage <= 0 ) if( MaxCountRemoveOfMessage <= 0 )
MaxCountRemoveOfMessage = 10; MaxCountRemoveOfMessage = 10;
recvMutexTimeout = conf->getArgPInt("--uniset-object-receive-mutex-timeout",conf->getField("RecvMutexTimeout"), 10000);
pushMutexTimeout = conf->getArgPInt("--uniset-object-push-mutex-timeout",conf->getField("PushMutexTimeout"), 9000);
if( unideb.debugging(Debug::INFO) ) if( unideb.debugging(Debug::INFO) )
{ {
unideb[Debug::INFO] << myname << "(init): SizeOfMessageQueue=" << SizeOfMessageQueue unideb[Debug::INFO] << myname << "(init): SizeOfMessageQueue=" << SizeOfMessageQueue
<< " MaxCountRemoveOfMessage=" << MaxCountRemoveOfMessage << " MaxCountRemoveOfMessage=" << MaxCountRemoveOfMessage
<< " recvMutexTimeout=" << recvMutexTimeout
<< " pushMutexTimeout=" << pushMutexTimeout
<< endl; << endl;
} }
} }
...@@ -198,7 +200,7 @@ void UniSetObject::setID( UniSetTypes::ObjectId id ) ...@@ -198,7 +200,7 @@ void UniSetObject::setID( UniSetTypes::ObjectId id )
bool UniSetObject::receiveMessage( VoidMessage& vm ) bool UniSetObject::receiveMessage( VoidMessage& vm )
{ {
{ // lock { // lock
uniset_mutex_lock mlk(qmutex, recvMutexTimeout); uniset_rwmutex_wrlock mlk(qmutex);
if( !queueMsg.empty() ) if( !queueMsg.empty() )
{ {
...@@ -374,10 +376,13 @@ void UniSetObject::registered() ...@@ -374,10 +376,13 @@ void UniSetObject::registered()
throw ORepFailed(err.c_str()); throw ORepFailed(err.c_str());
} }
if( !oref )
{ {
unideb[Debug::CRIT] << myname << "(registered): oref is NULL!..." << endl; UniSetTypes::uniset_rwmutex_rlock lock(refmutex);
return; if( !oref )
{
unideb[Debug::CRIT] << myname << "(registered): oref is NULL!..." << endl;
return;
}
} }
try try
...@@ -437,11 +442,14 @@ void UniSetObject::unregister() ...@@ -437,11 +442,14 @@ void UniSetObject::unregister()
return; return;
} }
if( !oref )
{ {
unideb[Debug::WARN] << myname << "(unregister): oref NULL!" << endl; UniSetTypes::uniset_rwmutex_rlock lock(refmutex);
reg = false; if( !oref )
return; {
unideb[Debug::WARN] << myname << "(unregister): oref NULL!" << endl;
reg = false;
return;
}
} }
...@@ -474,16 +482,6 @@ void UniSetObject::termWaiting() ...@@ -474,16 +482,6 @@ void UniSetObject::termWaiting()
tmr->terminate(); tmr->terminate();
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::setRecvMutexTimeout( unsigned long msec )
{
recvMutexTimeout = msec;
}
// ------------------------------------------------------------------------------------------
void UniSetObject::setPushMutexTimeout( unsigned long msec )
{
pushMutexTimeout = msec;
}
// ------------------------------------------------------------------------------------------
void UniSetObject::setThreadPriority( int p ) void UniSetObject::setThreadPriority( int p )
{ {
if( thr ) if( thr )
...@@ -493,7 +491,7 @@ void UniSetObject::setThreadPriority( int p ) ...@@ -493,7 +491,7 @@ void UniSetObject::setThreadPriority( int p )
void UniSetObject::push(const TransportMessage& tm) void UniSetObject::push(const TransportMessage& tm)
{ {
{ // lock { // lock
uniset_mutex_lock mlk(qmutex,pushMutexTimeout); uniset_rwmutex_wrlock mlk(qmutex);
// контроль переполнения // контроль переполнения
if( !queueMsg.empty() && queueMsg.size()>SizeOfMessageQueue ) if( !queueMsg.empty() && queueMsg.size()>SizeOfMessageQueue )
{ {
...@@ -718,7 +716,7 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q ) ...@@ -718,7 +716,7 @@ void UniSetObject::cleanMsgQueue( MessagesQueue& q )
unsigned int UniSetObject::countMessages() unsigned int UniSetObject::countMessages()
{ {
{ // lock { // lock
uniset_mutex_lock mlk(qmutex, 200); uniset_rwmutex_rlock mlk(qmutex);
return queueMsg.size(); return queueMsg.size();
} }
} }
...@@ -740,7 +738,7 @@ bool UniSetObject::disactivate() ...@@ -740,7 +738,7 @@ bool UniSetObject::disactivate()
// Очищаем очередь // Очищаем очередь
{ // lock { // lock
uniset_mutex_lock mlk(qmutex, 400); uniset_rwmutex_wrlock mlk(qmutex);
while( !queueMsg.empty() ) while( !queueMsg.empty() )
queueMsg.pop(); queueMsg.pop();
} }
...@@ -765,27 +763,33 @@ bool UniSetObject::disactivate() ...@@ -765,27 +763,33 @@ bool UniSetObject::disactivate()
unideb[Debug::INFO] << "ok..." << endl; unideb[Debug::INFO] << "ok..." << endl;
return true; return true;
} }
unideb[Debug::WARN] << "manager already destroyed.." << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "manager already destroyed.." << endl;
} }
catch(CORBA::TRANSIENT) catch(CORBA::TRANSIENT)
{ {
unideb[Debug::WARN] << "isExist: нет связи..."<< endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "isExist: нет связи..."<< endl;
} }
catch( CORBA::SystemException& ex ) catch( CORBA::SystemException& ex )
{ {
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::SystemException: " << ex.NP_minorString() << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::SystemException: " << ex.NP_minorString() << endl;
} }
catch(CORBA::Exception& ex) catch(CORBA::Exception& ex)
{ {
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::Exception." << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<<"поймали CORBA::Exception." << endl;
} }
catch(Exception& ex) catch(Exception& ex)
{ {
unideb[Debug::WARN] << "UniSetObject: "<< ex << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<< ex << endl;
} }
catch(...) catch(...)
{ {
unideb[Debug::WARN] << "UniSetObject: "<<" catch ..." << endl; if( unideb.debugging(Debug::WARN) )
unideb[Debug::WARN] << "UniSetObject: "<<" catch ..." << endl;
} }
return false; return false;
...@@ -841,7 +845,10 @@ bool UniSetObject::activate() ...@@ -841,7 +845,10 @@ bool UniSetObject::activate()
oref = poa->servant_to_reference(static_cast<PortableServer::ServantBase*>(this) ); {
UniSetTypes::uniset_rwmutex_wrlock lock(refmutex);
oref = poa->servant_to_reference(static_cast<PortableServer::ServantBase*>(this) );
}
registered(); registered();
// Запускаем поток обработки сообщений // Запускаем поток обработки сообщений
...@@ -951,13 +958,13 @@ bool UniSetObject::PriorVMsgCompare::operator()(const UniSetTypes::VoidMessage& ...@@ -951,13 +958,13 @@ bool UniSetObject::PriorVMsgCompare::operator()(const UniSetTypes::VoidMessage&
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
void UniSetObject::setActive( bool set ) void UniSetObject::setActive( bool set )
{ {
uniset_mutex_lock l(act_mutex,300); uniset_rwmutex_wrlock l(mutex_act);
active = set; active = set;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
bool UniSetObject::isActive() bool UniSetObject::isActive()
{ {
uniset_mutex_lock l(act_mutex,200); uniset_rwmutex_rlock l(mutex_act);
return active; return active;
} }
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
......
...@@ -45,7 +45,7 @@ IOController::IOController(const string name, const string section): ...@@ -45,7 +45,7 @@ IOController::IOController(const string name, const string section):
dioMutex(name+"_dioMutex"), dioMutex(name+"_dioMutex"),
aioMutex(name+"_aioMutex"), aioMutex(name+"_aioMutex"),
isPingDBServer(true), isPingDBServer(true),
checkLockValuePause(0) checkLockValuePause(5)
{ {
} }
...@@ -54,7 +54,7 @@ IOController::IOController(ObjectId id): ...@@ -54,7 +54,7 @@ IOController::IOController(ObjectId id):
dioMutex(string(conf->oind->getMapName(id))+"_dioMutex"), dioMutex(string(conf->oind->getMapName(id))+"_dioMutex"),
aioMutex(string(conf->oind->getMapName(id))+"_aioMutex"), aioMutex(string(conf->oind->getMapName(id))+"_aioMutex"),
isPingDBServer(true), isPingDBServer(true),
checkLockValuePause(0) checkLockValuePause(5)
{ {
} }
...@@ -151,7 +151,7 @@ bool IOController::localGetState( IOController::DIOStateList::iterator& li, ...@@ -151,7 +151,7 @@ bool IOController::localGetState( IOController::DIOStateList::iterator& li,
if( li->second.undefined ) if( li->second.undefined )
throw IOController_i::Undefined(); throw IOController_i::Undefined();
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(li->second.val_lock,checkLockValuePause);
return li->second.state; return li->second.state;
} }
...@@ -176,7 +176,7 @@ long IOController::localGetValue( IOController::AIOStateList::iterator& li, ...@@ -176,7 +176,7 @@ long IOController::localGetValue( IOController::AIOStateList::iterator& li,
if( li->second.undefined ) if( li->second.undefined )
throw IOController_i::Undefined(); throw IOController_i::Undefined();
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(li->second.val_lock,checkLockValuePause);
return li->second.value; return li->second.value;
} }
...@@ -233,7 +233,7 @@ void IOController::localSetUndefinedState( AIOStateList::iterator& li, ...@@ -233,7 +233,7 @@ void IOController::localSetUndefinedState( AIOStateList::iterator& li,
} }
{ // lock { // lock
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_wrlock lock(li->second.val_lock);
li->second.undefined = undefined; li->second.undefined = undefined;
updateDepends( li->second.dlst, undefined, li->second.dlst_lock ); updateDepends( li->second.dlst, undefined, li->second.dlst_lock );
} // unlock } // unlock
...@@ -270,7 +270,7 @@ void IOController::localSaveState( IOController::DIOStateList::iterator& li, ...@@ -270,7 +270,7 @@ void IOController::localSaveState( IOController::DIOStateList::iterator& li,
} }
// { // lock // { // lock
// uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); // uniset_rwmutex_lock wrlock(li->second.val_lock,checkLockValuePause);
bool changed = false; bool changed = false;
bool blk_set = false; bool blk_set = false;
bool blocked = ( li->second.blocked || li->second.undefined ); bool blocked = ( li->second.blocked || li->second.undefined );
...@@ -278,7 +278,7 @@ void IOController::localSaveState( IOController::DIOStateList::iterator& li, ...@@ -278,7 +278,7 @@ void IOController::localSaveState( IOController::DIOStateList::iterator& li,
if( checkDFilters(&li->second,state,sup_id) || blocked ) if( checkDFilters(&li->second,state,sup_id) || blocked )
{ {
{ // lock { // lock
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_wrlock lock(li->second.val_lock);
if( !blocked ) if( !blocked )
li->second.real_state = li->second.state; li->second.real_state = li->second.state;
...@@ -378,7 +378,7 @@ void IOController::localSaveValue( IOController::AIOStateList::iterator& li, ...@@ -378,7 +378,7 @@ void IOController::localSaveValue( IOController::AIOStateList::iterator& li,
} }
{ // lock { // lock
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_wrlock lock(li->second.val_lock);
// фильтрам может потребоваться измениять исходное значение (например для усреднения) // фильтрам может потребоваться измениять исходное значение (например для усреднения)
// поэтому передаём (и затем сохраняем) напрямую(ссылку) value (а не const value) // поэтому передаём (и затем сохраняем) напрямую(ссылку) value (а не const value)
...@@ -500,7 +500,7 @@ void IOController::localSetState( IOController::DIOStateList::iterator& li, ...@@ -500,7 +500,7 @@ void IOController::localSetState( IOController::DIOStateList::iterator& li,
bool blk_set = false; bool blk_set = false;
{ // lock { // lock
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_wrlock lock(li->second.val_lock);
blocked = ( li->second.blocked || li->second.undefined ); blocked = ( li->second.blocked || li->second.undefined );
if ( !blocked ) if ( !blocked )
...@@ -566,7 +566,7 @@ void IOController::localSetValue( IOController::AIOStateList::iterator& li, ...@@ -566,7 +566,7 @@ void IOController::localSetValue( IOController::AIOStateList::iterator& li,
if( li!=aioList.end() && li->second.type == UniversalIO::AnalogOutput ) if( li!=aioList.end() && li->second.type == UniversalIO::AnalogOutput )
{ {
{ // lock { // lock
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_wrlock lock(li->second.val_lock);
if( li->second.blocked ) if( li->second.blocked )
li->second.real_value = value; li->second.real_value = value;
...@@ -616,7 +616,7 @@ void IOController::dsRegistration( const UniDigitalIOInfo& dinf, bool force ) ...@@ -616,7 +616,7 @@ void IOController::dsRegistration( const UniDigitalIOInfo& dinf, bool force )
UniSetTypes::KeyType k = key(dinf.si.id, dinf.si.node); UniSetTypes::KeyType k = key(dinf.si.id, dinf.si.node);
{ // lock { // lock
uniset_mutex_lock lock(dioMutex, 500); uniset_rwmutex_wrlock lock(dioMutex);
if( !force ) if( !force )
{ {
DIOStateList::iterator li = dioList.find(k); DIOStateList::iterator li = dioList.find(k);
...@@ -694,7 +694,7 @@ void IOController::asRegistration( const UniAnalogIOInfo& ainf, bool force ) ...@@ -694,7 +694,7 @@ void IOController::asRegistration( const UniAnalogIOInfo& ainf, bool force )
UniSetTypes::KeyType k = key(ainf.si.id, ainf.si.node); UniSetTypes::KeyType k = key(ainf.si.id, ainf.si.node);
{ // lock { // lock
uniset_mutex_lock lock(aioMutex, 500); uniset_rwmutex_wrlock lock(aioMutex);
if( !force ) if( !force )
{ {
AIOStateList::iterator li = aioList.find(k); AIOStateList::iterator li = aioList.find(k);
...@@ -767,6 +767,7 @@ void IOController::sUnRegistration( const IOController_i::SensorInfo& si ) ...@@ -767,6 +767,7 @@ void IOController::sUnRegistration( const IOController_i::SensorInfo& si )
void IOController::logging( UniSetTypes::SensorMessage& sm ) void IOController::logging( UniSetTypes::SensorMessage& sm )
{ {
uniset_rwmutex_wrlock l(loggingMutex);
try try
{ {
// struct timezone tz; // struct timezone tz;
...@@ -778,18 +779,16 @@ void IOController::logging( UniSetTypes::SensorMessage& sm ) ...@@ -778,18 +779,16 @@ void IOController::logging( UniSetTypes::SensorMessage& sm )
sm.consumer = dbID; sm.consumer = dbID;
TransportMessage tm(sm.transport_msg()); TransportMessage tm(sm.transport_msg());
{ ui.send(sm.consumer, tm);
uniset_mutex_lock l(loggingMutex,300); isPingDBServer = true;
ui.send(sm.consumer, tm);
isPingDBServer = true;
}
} }
catch(...) catch(...)
{ {
if(isPingDBServer) if( isPingDBServer )
{ {
unideb[Debug::CRIT] << myname << "(logging): DBServer unavailable" << endl;
isPingDBServer = false; isPingDBServer = false;
if( unideb.debugging(Debug::CRIT) )
unideb[Debug::CRIT] << myname << "(logging): DBServer unavailable" << endl;
} }
} }
} }
...@@ -805,7 +804,7 @@ void IOController::dumpToDB() ...@@ -805,7 +804,7 @@ void IOController::dumpToDB()
// uniset_mutex_lock lock(dioMutex, 100); // uniset_mutex_lock lock(dioMutex, 100);
for( DIOStateList::iterator li = dioList.begin(); li!=dioList.end(); ++li ) for( DIOStateList::iterator li = dioList.begin(); li!=dioList.end(); ++li )
{ {
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(li->second.val_lock,checkLockValuePause);
SensorMessage sm; SensorMessage sm;
sm.id = li->second.si.id; sm.id = li->second.si.id;
sm.node = li->second.si.node; sm.node = li->second.si.node;
...@@ -826,7 +825,7 @@ void IOController::dumpToDB() ...@@ -826,7 +825,7 @@ void IOController::dumpToDB()
// uniset_mutex_lock lock(aioMutex, 100); // uniset_mutex_lock lock(aioMutex, 100);
for( AIOStateList::iterator li = aioList.begin(); li!=aioList.end(); ++li ) for( AIOStateList::iterator li = aioList.begin(); li!=aioList.end(); ++li )
{ {
uniset_spin_lock lock(li->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(li->second.val_lock,checkLockValuePause);
SensorMessage sm; SensorMessage sm;
sm.id = li->second.si.id; sm.id = li->second.si.id;
sm.node = li->second.si.node; sm.node = li->second.si.node;
...@@ -856,7 +855,7 @@ IOController_i::ASensorInfoSeq* IOController::getAnalogSensorsMap() ...@@ -856,7 +855,7 @@ IOController_i::ASensorInfoSeq* IOController::getAnalogSensorsMap()
int i=0; int i=0;
for( AIOStateList::iterator it=aioList.begin(); it!=aioList.end(); ++it) for( AIOStateList::iterator it=aioList.begin(); it!=aioList.end(); ++it)
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
(*res)[i] = it->second; (*res)[i] = it->second;
i++; i++;
} }
...@@ -877,7 +876,7 @@ IOController_i::DSensorInfoSeq* IOController::getDigitalSensorsMap() ...@@ -877,7 +876,7 @@ IOController_i::DSensorInfoSeq* IOController::getDigitalSensorsMap()
int i=0; int i=0;
for( DIOStateList::iterator it= dioList.begin(); it!=dioList.end(); ++it) for( DIOStateList::iterator it= dioList.begin(); it!=dioList.end(); ++it)
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
(*res)[i].si = it->second.si; (*res)[i].si = it->second.si;
(*res)[i].type = it->second.type; (*res)[i].type = it->second.type;
(*res)[i].state = it->second.state; (*res)[i].state = it->second.state;
...@@ -934,7 +933,7 @@ IOController_i::DigitalIOInfo IOController::getDInfo(const IOController_i::Senso ...@@ -934,7 +933,7 @@ IOController_i::DigitalIOInfo IOController::getDInfo(const IOController_i::Senso
DIOStateList::iterator it = dioList.find( key(si.id, si.node) ); DIOStateList::iterator it = dioList.find( key(si.id, si.node) );
if( it!=dioList.end() ) if( it!=dioList.end() )
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
return it->second; return it->second;
} }
...@@ -954,7 +953,7 @@ IOController_i::AnalogIOInfo IOController::getAInfo(const IOController_i::Sensor ...@@ -954,7 +953,7 @@ IOController_i::AnalogIOInfo IOController::getAInfo(const IOController_i::Sensor
AIOStateList::iterator it = aioList.find( key(si.id, si.node) ); AIOStateList::iterator it = aioList.find( key(si.id, si.node) );
if( it!=aioList.end() ) if( it!=aioList.end() )
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
return it->second; return it->second;
} }
...@@ -1333,7 +1332,7 @@ IOController_i::ASensorInfoSeq* IOController::getSensorSeq( const IDSeq& lst ) ...@@ -1333,7 +1332,7 @@ IOController_i::ASensorInfoSeq* IOController::getSensorSeq( const IDSeq& lst )
DIOStateList::iterator it = dioList.find( UniSetTypes::key(lst[i],conf->getLocalNode()) ); DIOStateList::iterator it = dioList.find( UniSetTypes::key(lst[i],conf->getLocalNode()) );
if( it!=dioList.end() ) if( it!=dioList.end() )
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
(*res)[i].si = it->second.si; (*res)[i].si = it->second.si;
(*res)[i].type = it->second.type; (*res)[i].type = it->second.type;
(*res)[i].real_value= it->second.real_state ? 1 : 0; (*res)[i].real_value= it->second.real_state ? 1 : 0;
...@@ -1353,7 +1352,7 @@ IOController_i::ASensorInfoSeq* IOController::getSensorSeq( const IDSeq& lst ) ...@@ -1353,7 +1352,7 @@ IOController_i::ASensorInfoSeq* IOController::getSensorSeq( const IDSeq& lst )
AIOStateList::iterator it = aioList.find( UniSetTypes::key(lst[i],conf->getLocalNode()) ); AIOStateList::iterator it = aioList.find( UniSetTypes::key(lst[i],conf->getLocalNode()) );
if( it!=aioList.end() ) if( it!=aioList.end() )
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
(*res)[i] = it->second; (*res)[i] = it->second;
continue; continue;
} }
...@@ -1414,7 +1413,7 @@ IOController_i::ShortIOInfo IOController::getChangedTime( const IOController_i:: ...@@ -1414,7 +1413,7 @@ IOController_i::ShortIOInfo IOController::getChangedTime( const IOController_i::
if( dit!=dioList.end() ) if( dit!=dioList.end() )
{ {
IOController_i::ShortIOInfo i; IOController_i::ShortIOInfo i;
uniset_spin_lock lock(dit->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(dit->second.val_lock,checkLockValuePause);
i.value = dit->second.state ? 1 : 0; i.value = dit->second.state ? 1 : 0;
i.tv_sec = dit->second.tv_sec; i.tv_sec = dit->second.tv_sec;
i.tv_usec = dit->second.tv_usec; i.tv_usec = dit->second.tv_usec;
...@@ -1425,7 +1424,7 @@ IOController_i::ShortIOInfo IOController::getChangedTime( const IOController_i:: ...@@ -1425,7 +1424,7 @@ IOController_i::ShortIOInfo IOController::getChangedTime( const IOController_i::
if( ait!=aioList.end() ) if( ait!=aioList.end() )
{ {
IOController_i::ShortIOInfo i; IOController_i::ShortIOInfo i;
uniset_spin_lock lock(ait->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(ait->second.val_lock,checkLockValuePause);
i.value = ait->second.value; i.value = ait->second.value;
i.tv_sec = ait->second.tv_sec; i.tv_sec = ait->second.tv_sec;
i.tv_usec = ait->second.tv_usec; i.tv_usec = ait->second.tv_usec;
...@@ -1452,7 +1451,7 @@ IOController_i::ShortMapSeq* IOController::getSensors() ...@@ -1452,7 +1451,7 @@ IOController_i::ShortMapSeq* IOController::getSensors()
{ {
IOController_i::ShortMap m; IOController_i::ShortMap m;
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
m.id = it->second.si.id; m.id = it->second.si.id;
m.value = it->second.value; m.value = it->second.value;
m.type = it->second.type; m.type = it->second.type;
...@@ -1463,7 +1462,7 @@ IOController_i::ShortMapSeq* IOController::getSensors() ...@@ -1463,7 +1462,7 @@ IOController_i::ShortMapSeq* IOController::getSensors()
{ {
IOController_i::ShortMap m; IOController_i::ShortMap m;
{ {
uniset_spin_lock lock(it->second.val_lock,checkLockValuePause); uniset_rwmutex_rlock lock(it->second.val_lock,checkLockValuePause);
m.id = it->second.si.id; m.id = it->second.si.id;
m.value = it->second.state ? 1 : 0; m.value = it->second.state ? 1 : 0;
m.type = it->second.type; m.type = it->second.type;
......
...@@ -226,9 +226,9 @@ void IONotifyController::askState( const IOController_i::SensorInfo& si, ...@@ -226,9 +226,9 @@ void IONotifyController::askState( const IOController_i::SensorInfo& si,
} }
{ //lock { //lock
uniset_mutex_lock lock(askDMutex, 200); uniset_rwmutex_wrlock lock(askDMutex);
// а раз есть заносим(исключаем) заказчика // а раз есть заносим(исключаем) заказчика
ask( askDIOList, si, ci, cmd); ask( askDIOList, si, ci, cmd);
} // unlock } // unlock
// посылка первый раз состояния // посылка первый раз состояния
...@@ -242,7 +242,7 @@ void IONotifyController::askState( const IOController_i::SensorInfo& si, ...@@ -242,7 +242,7 @@ void IONotifyController::askState( const IOController_i::SensorInfo& si,
smsg.priority = (Message::Priority)li->second.priority; smsg.priority = (Message::Priority)li->second.priority;
smsg.supplier = getId(); smsg.supplier = getId();
{ {
uniset_spin_lock lock(li->second.val_lock,getCheckLockValuePause()); uniset_rwmutex_rlock lock(li->second.val_lock,getCheckLockValuePause());
smsg.state = li->second.state; smsg.state = li->second.state;
smsg.value = li->second.state ? 1:0; smsg.value = li->second.state ? 1:0;
smsg.undefined = li->second.undefined; smsg.undefined = li->second.undefined;
...@@ -305,7 +305,7 @@ void IONotifyController::askValue(const IOController_i::SensorInfo& si, ...@@ -305,7 +305,7 @@ void IONotifyController::askValue(const IOController_i::SensorInfo& si,
} }
{ // lock { // lock
uniset_mutex_lock lock(askAMutex, 200); uniset_rwmutex_wrlock lock(askAMutex);
// а раз есть заносим(исключаем) заказчика // а раз есть заносим(исключаем) заказчика
ask( askAIOList, si, ci, cmd); ask( askAIOList, si, ci, cmd);
} // unlock } // unlock
...@@ -324,7 +324,7 @@ void IONotifyController::askValue(const IOController_i::SensorInfo& si, ...@@ -324,7 +324,7 @@ void IONotifyController::askValue(const IOController_i::SensorInfo& si,
smsg.sm_tv_usec = li->second.tv_usec; smsg.sm_tv_usec = li->second.tv_usec;
smsg.ci = li->second.ci; smsg.ci = li->second.ci;
{ {
uniset_spin_lock lock(li->second.val_lock,getCheckLockValuePause()); uniset_rwmutex_rlock lock(li->second.val_lock,getCheckLockValuePause());
smsg.value = li->second.value; smsg.value = li->second.value;
smsg.state = li->second.value ? true:false; smsg.state = li->second.value ? true:false;
smsg.undefined = li->second.undefined; smsg.undefined = li->second.undefined;
...@@ -475,7 +475,7 @@ void IONotifyController::localSaveState( IOController::DIOStateList::iterator& i ...@@ -475,7 +475,7 @@ void IONotifyController::localSaveState( IOController::DIOStateList::iterator& i
// фильтрами или блокировками.. // фильтрами или блокировками..
SensorMessage sm(si.id, state); SensorMessage sm(si.id, state);
{ // lock { // lock
uniset_spin_lock lock(it->second.val_lock,getCheckLockValuePause()); uniset_rwmutex_rlock lock(it->second.val_lock,getCheckLockValuePause());
if( prevState == it->second.state ) if( prevState == it->second.state )
return; return;
...@@ -494,7 +494,7 @@ void IONotifyController::localSaveState( IOController::DIOStateList::iterator& i ...@@ -494,7 +494,7 @@ void IONotifyController::localSaveState( IOController::DIOStateList::iterator& i
try try
{ {
uniset_mutex_lock l(sig_mutex,500); uniset_rwmutex_rlock l(sig_mutex);
changeSignal.emit(&sm); changeSignal.emit(&sm);
} }
catch(...){} catch(...){}
...@@ -509,7 +509,8 @@ void IONotifyController::localSaveState( IOController::DIOStateList::iterator& i ...@@ -509,7 +509,8 @@ void IONotifyController::localSaveState( IOController::DIOStateList::iterator& i
AskMap::iterator it1 = askDIOList.find( key(si.id,si.node) ); AskMap::iterator it1 = askDIOList.find( key(si.id,si.node) );
if( it1!=askDIOList.end() ) if( it1!=askDIOList.end() )
{ // lock { // lock
uniset_mutex_lock lock(askDMutex, 1000); //uniset_mutex_lock lock(askDMutex, 1000);
uniset_rwmutex_rlock lock(askDMutex);
send(it1->second, sm); send(it1->second, sm);
} // unlock } // unlock
} }
...@@ -538,7 +539,7 @@ void IONotifyController::localSaveValue( IOController::AIOStateList::iterator& l ...@@ -538,7 +539,7 @@ void IONotifyController::localSaveValue( IOController::AIOStateList::iterator& l
// фильтрами или блокировками.. // фильтрами или блокировками..
SensorMessage sm(si.id,li->second.value); SensorMessage sm(si.id,li->second.value);
{ // lock { // lock
uniset_spin_lock lock(li->second.val_lock,getCheckLockValuePause()); uniset_rwmutex_rlock lock(li->second.val_lock,getCheckLockValuePause());
if( prevValue == li->second.value ) if( prevValue == li->second.value )
return; return;
...@@ -559,7 +560,8 @@ void IONotifyController::localSaveValue( IOController::AIOStateList::iterator& l ...@@ -559,7 +560,8 @@ void IONotifyController::localSaveValue( IOController::AIOStateList::iterator& l
try try
{ {
uniset_mutex_lock l(sig_mutex,500); //uniset_mutex_rlock l(sig_mutex,500);
uniset_rwmutex_rlock l(sig_mutex);
changeSignal.emit(&sm); changeSignal.emit(&sm);
} }
catch(...){} catch(...){}
...@@ -574,7 +576,7 @@ void IONotifyController::localSaveValue( IOController::AIOStateList::iterator& l ...@@ -574,7 +576,7 @@ void IONotifyController::localSaveValue( IOController::AIOStateList::iterator& l
AskMap::iterator it = askAIOList.find( key(si.id,si.node) ); AskMap::iterator it = askAIOList.find( key(si.id,si.node) );
if( it!=askAIOList.end() ) if( it!=askAIOList.end() )
{ // lock { // lock
uniset_mutex_lock lock(askAMutex, 1000); uniset_rwmutex_rlock lock(askAMutex);
send(it->second, sm); send(it->second, sm);
} }
...@@ -759,7 +761,7 @@ void IONotifyController::askThreshold(const IOController_i::SensorInfo& si, cons ...@@ -759,7 +761,7 @@ void IONotifyController::askThreshold(const IOController_i::SensorInfo& si, cons
CORBA::Long val = localGetValue(li,si); CORBA::Long val = localGetValue(li,si);
{ // lock { // lock
uniset_mutex_lock lock(trshMutex, 300); uniset_rwmutex_wrlock lock(trshMutex);
// поиск датчика в списке // поиск датчика в списке
UniSetTypes::KeyType skey( key(si.id,si.node) ); UniSetTypes::KeyType skey( key(si.id,si.node) );
...@@ -949,7 +951,7 @@ void IONotifyController::checkThreshold( AIOStateList::iterator& li, ...@@ -949,7 +951,7 @@ void IONotifyController::checkThreshold( AIOStateList::iterator& li,
bool send_msg ) bool send_msg )
{ {
{ // lock { // lock
uniset_mutex_lock lock(trshMutex, 300); uniset_rwmutex_rlock lock(trshMutex);
// поиск списка порогов // поиск списка порогов
UniSetTypes::KeyType skey( key(si.id,si.node) ); UniSetTypes::KeyType skey( key(si.id,si.node) );
...@@ -973,7 +975,7 @@ void IONotifyController::checkThreshold( AIOStateList::iterator& li, ...@@ -973,7 +975,7 @@ void IONotifyController::checkThreshold( AIOStateList::iterator& li,
sm.priority = (Message::Priority)li->second.priority; sm.priority = (Message::Priority)li->second.priority;
sm.ci = li->second.ci; sm.ci = li->second.ci;
{ {
uniset_spin_lock lock(li->second.val_lock,getCheckLockValuePause()); uniset_rwmutex_rlock lock(li->second.val_lock,getCheckLockValuePause());
sm.value = li->second.value; sm.value = li->second.value;
sm.state = li->second.value!=0 ? true:false; sm.state = li->second.value!=0 ? true:false;
sm.undefined = li->second.undefined; sm.undefined = li->second.undefined;
...@@ -1096,7 +1098,7 @@ void IONotifyController::askOutput(const IOController_i::SensorInfo& si, ...@@ -1096,7 +1098,7 @@ void IONotifyController::askOutput(const IOController_i::SensorInfo& si,
{ {
case UniversalIO::DigitalOutput: case UniversalIO::DigitalOutput:
{ //lock { //lock
uniset_mutex_lock lock(askDOMutex, 200); uniset_rwmutex_wrlock lock(askDOMutex);
// а раз есть заносим(исключаем) заказчика // а раз есть заносим(исключаем) заказчика
ask( askDOList, si, ci, cmd ); ask( askDOList, si, ci, cmd );
} // unlock } // unlock
...@@ -1104,7 +1106,7 @@ void IONotifyController::askOutput(const IOController_i::SensorInfo& si, ...@@ -1104,7 +1106,7 @@ void IONotifyController::askOutput(const IOController_i::SensorInfo& si,
case UniversalIO::AnalogOutput: case UniversalIO::AnalogOutput:
{ //lock { //lock
uniset_mutex_lock lock(askAOMutex, 200); uniset_rwmutex_wrlock lock(askAOMutex);
// а раз есть заносим(исключаем) заказчика // а раз есть заносим(исключаем) заказчика
ask( askAOList, si, ci, cmd ); ask( askAOList, si, ci, cmd );
} // unlock } // unlock
...@@ -1189,7 +1191,7 @@ void IONotifyController::localSetState( IOController::DIOStateList::iterator& it ...@@ -1189,7 +1191,7 @@ void IONotifyController::localSetState( IOController::DIOStateList::iterator& it
// Рассылаем уведомления только если значение изменилось... // Рассылаем уведомления только если значение изменилось...
SensorMessage sm(si.id, state); SensorMessage sm(si.id, state);
{ // lock { // lock
uniset_spin_lock lock(it->second.val_lock,getCheckLockValuePause()); uniset_rwmutex_rlock lock(it->second.val_lock,getCheckLockValuePause());
if( prevState == it->second.state ) if( prevState == it->second.state )
return; return;
sm.id = si.id; sm.id = si.id;
...@@ -1206,7 +1208,7 @@ void IONotifyController::localSetState( IOController::DIOStateList::iterator& it ...@@ -1206,7 +1208,7 @@ void IONotifyController::localSetState( IOController::DIOStateList::iterator& it
try try
{ {
uniset_mutex_lock l(sig_mutex,500); uniset_rwmutex_rlock l(sig_mutex);
changeSignal.emit(&sm); changeSignal.emit(&sm);
} }
catch(...){} catch(...){}
...@@ -1222,7 +1224,7 @@ void IONotifyController::localSetState( IOController::DIOStateList::iterator& it ...@@ -1222,7 +1224,7 @@ void IONotifyController::localSetState( IOController::DIOStateList::iterator& it
AskMap::iterator ait = askDOList.find( UniSetTypes::key(si.id,si.node) ); AskMap::iterator ait = askDOList.find( UniSetTypes::key(si.id,si.node) );
if( ait!=askDOList.end() ) if( ait!=askDOList.end() )
{ // lock { // lock
uniset_mutex_lock lock(askDMutex, 200); uniset_rwmutex_rlock lock(askDMutex);
send(ait->second, sm); send(ait->second, sm);
} // unlock } // unlock
} }
...@@ -1245,7 +1247,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li ...@@ -1245,7 +1247,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li
// Рассылаем уведомления только если значение изменилось... // Рассылаем уведомления только если значение изменилось...
SensorMessage sm; SensorMessage sm;
{ // lock { // lock
uniset_spin_lock lock(li->second.val_lock,getCheckLockValuePause()); uniset_rwmutex_rlock lock(li->second.val_lock,getCheckLockValuePause());
if( prevValue == li->second.value ) if( prevValue == li->second.value )
return; return;
...@@ -1264,7 +1266,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li ...@@ -1264,7 +1266,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li
try try
{ {
uniset_mutex_lock l(sig_mutex,500); uniset_rwmutex_rlock l(sig_mutex);
changeSignal.emit(&sm); changeSignal.emit(&sm);
} }
catch(...){} catch(...){}
...@@ -1279,7 +1281,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li ...@@ -1279,7 +1281,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li
AskMap::iterator dit = askAOList.find( UniSetTypes::key(si.id,si.node) ); AskMap::iterator dit = askAOList.find( UniSetTypes::key(si.id,si.node) );
if( dit!=askAOList.end() ) if( dit!=askAOList.end() )
{ // lock { // lock
uniset_mutex_lock lock(askAMutex, 200); uniset_rwmutex_rlock lock(askAMutex);
send(dit->second, sm); send(dit->second, sm);
} }
...@@ -1296,7 +1298,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li ...@@ -1296,7 +1298,7 @@ void IONotifyController::localSetValue( IOController::AIOStateList::iterator& li
IONotifyController::ThresholdExtList::iterator IONotifyController::findThreshold( UniSetTypes::KeyType key, UniSetTypes::ThresholdId tid ) IONotifyController::ThresholdExtList::iterator IONotifyController::findThreshold( UniSetTypes::KeyType key, UniSetTypes::ThresholdId tid )
{ {
{ // lock { // lock
uniset_mutex_lock lock(trshMutex, 300); uniset_rwmutex_rlock lock(trshMutex);
// поиск списка порогов // поиск списка порогов
// UniSetTypes::KeyType skey( key(si.id,si.node) ); // UniSetTypes::KeyType skey( key(si.id,si.node) );
AskThresholdMap::iterator lst = askTMap.find(key); AskThresholdMap::iterator lst = askTMap.find(key);
...@@ -1416,7 +1418,7 @@ void IONotifyController::onChangeUndefined( DependsList::iterator it, bool undef ...@@ -1416,7 +1418,7 @@ void IONotifyController::onChangeUndefined( DependsList::iterator it, bool undef
AskMap::iterator it1 = askDIOList.find( key(it->si.id,it->si.node) ); AskMap::iterator it1 = askDIOList.find( key(it->si.id,it->si.node) );
if( it1!=askDIOList.end() ) if( it1!=askDIOList.end() )
{ // lock { // lock
uniset_mutex_lock lock(askDMutex, 1000); uniset_rwmutex_rlock lock(askDMutex);
send(it1->second, sm); send(it1->second, sm);
} // unlock } // unlock
} }
......
...@@ -28,7 +28,6 @@ ...@@ -28,7 +28,6 @@
#include <pthread.h> #include <pthread.h>
#include <time.h> #include <time.h>
#include "PosixThread.h"
#include "PassiveTimer.h" #include "PassiveTimer.h"
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
......
...@@ -33,6 +33,7 @@ using namespace UniSetTypes; ...@@ -33,6 +33,7 @@ using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
LT_Object::LT_Object(): LT_Object::LT_Object():
lstMutex("LT_Object::lstMutex"),
sleepTime(UniSetTimer::WaitUpTime) sleepTime(UniSetTimer::WaitUpTime)
{ {
tmLast.setTiming(UniSetTimer::WaitUpTime); tmLast.setTiming(UniSetTimer::WaitUpTime);
...@@ -48,7 +49,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj ) ...@@ -48,7 +49,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
try try
{ {
{ // lock { // lock
uniset_mutex_lock lock(lstMutex, 5000); uniset_rwmutex_rlock lock(lstMutex, 5000);
if( tlst.empty() ) if( tlst.empty() )
{ {
...@@ -70,7 +71,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj ) ...@@ -70,7 +71,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
} }
{ // lock { // lock
uniset_mutex_lock lock(lstMutex, 5000); 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)
{ {
...@@ -130,10 +131,7 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c ...@@ -130,10 +131,7 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c
} }
{ // lock { // lock
if( unideb.debugging(Debug::INFO) && !lstMutex.isRelease() ) uniset_rwmutex_wrlock lock(lstMutex);
unideb[Debug::INFO] << "(LT_askTimer): придется подождать освобождения lstMutex-а" << endl;
uniset_mutex_lock lock(lstMutex, 2000);
// поищем а может уж такой есть // поищем а может уж такой есть
if( !tlst.empty() ) if( !tlst.empty() )
{ {
...@@ -166,20 +164,13 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c ...@@ -166,20 +164,13 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c
if( unideb.debugging(Debug::INFO) ) if( unideb.debugging(Debug::INFO) )
unideb[Debug::INFO] << "(LT_askTimer): поступил отказ по таймеру id="<< timerid << endl; unideb[Debug::INFO] << "(LT_askTimer): поступил отказ по таймеру id="<< timerid << endl;
{ // lock { // lock
if( unideb.debugging(Debug::INFO) && !lstMutex.isRelease() ) uniset_rwmutex_wrlock lock(lstMutex);
unideb[Debug::INFO] << "(LT_askTimer): придется подождать освобождения lstMutex-а\n";
uniset_mutex_lock lock(lstMutex, 2000);
tlst.remove_if(Timer_eq(timerid)); // STL - способ tlst.remove_if(Timer_eq(timerid)); // STL - способ
} // unlock } // unlock
} }
{ // lock { // lock
if( unideb.debugging(Debug::INFO) && !lstMutex.isRelease() ) uniset_rwmutex_rlock lock(lstMutex);
unideb[Debug::INFO] << "(LT_askTimer): придется подождать освобождения lstMutex-а\n";
uniset_mutex_lock lock(lstMutex, 2000);
if( tlst.empty() ) if( tlst.empty() )
sleepTime = UniSetTimer::WaitUpTime; sleepTime = UniSetTimer::WaitUpTime;
......
...@@ -31,6 +31,8 @@ ...@@ -31,6 +31,8 @@
using namespace std; using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#define MUTEX_DEBUG(m) {}
uniset_mutex::uniset_mutex(): uniset_mutex::uniset_mutex():
cnd(0), cnd(0),
nm(""), nm(""),
...@@ -52,15 +54,23 @@ uniset_mutex::~uniset_mutex() ...@@ -52,15 +54,23 @@ uniset_mutex::~uniset_mutex()
delete cnd; delete cnd;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
std::ostream& UniSetTypes::operator<<(std::ostream& os, uniset_mutex& m )
{
return os << m.name();
}
// -----------------------------------------------------------------------------
void uniset_mutex::lock() void uniset_mutex::lock()
{ {
sem.wait(); sem.wait();
locked = 1; locked = 1;
MUTEX_DEBUG(cerr << nm << " Locked.." << endl;)
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
void uniset_mutex::unlock() void uniset_mutex::unlock()
{ {
locked = 0; locked = 0;
MUTEX_DEBUG(cerr << nm << " Unlocked.." << endl;)
sem.post(); sem.post();
cnd->signal(); cnd->signal();
} }
...@@ -138,16 +148,29 @@ uniset_mutex_lock& uniset_mutex_lock::operator=(const uniset_mutex_lock &r) ...@@ -138,16 +148,29 @@ uniset_mutex_lock& uniset_mutex_lock::operator=(const uniset_mutex_lock &r)
return *this; return *this;
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
uniset_spin_mutex::uniset_spin_mutex(): uniset_rwmutex::uniset_rwmutex( const std::string& name ):
nm(name),
wr_wait(0) wr_wait(0)
{ {
}
uniset_rwmutex::uniset_rwmutex():
wr_wait(0)
{
}
uniset_rwmutex::~uniset_rwmutex()
{
} }
uniset_spin_mutex::~uniset_spin_mutex() std::ostream& UniSetTypes::operator<<(std::ostream& os, uniset_rwmutex& m )
{ {
return os << m.name();
} }
const uniset_spin_mutex &uniset_spin_mutex::operator=( const uniset_spin_mutex& r )
const uniset_rwmutex &uniset_rwmutex::operator=( const uniset_rwmutex& r )
{ {
if( this != &r ) if( this != &r )
unlock(); unlock();
...@@ -155,12 +178,12 @@ const uniset_spin_mutex &uniset_spin_mutex::operator=( const uniset_spin_mutex& ...@@ -155,12 +178,12 @@ const uniset_spin_mutex &uniset_spin_mutex::operator=( const uniset_spin_mutex&
return *this; return *this;
} }
uniset_spin_mutex::uniset_spin_mutex( const uniset_spin_mutex& r ) uniset_rwmutex::uniset_rwmutex( const uniset_rwmutex& r )
{ {
//unlock(); //unlock();
} }
void uniset_spin_mutex::lock( int check_pause_msec ) void uniset_rwmutex::lock( int check_pause_msec )
{ {
wr_wait += 1; wr_wait += 1;
while( !m.tryWriteLock() ) while( !m.tryWriteLock() )
...@@ -169,8 +192,9 @@ void uniset_spin_mutex::lock( int check_pause_msec ) ...@@ -169,8 +192,9 @@ void uniset_spin_mutex::lock( int check_pause_msec )
msleep(check_pause_msec); msleep(check_pause_msec);
} }
wr_wait -= 1; wr_wait -= 1;
MUTEX_DEBUG(cerr << nm << " Locked.." << endl;)
} }
void uniset_spin_mutex::wrlock( int check_pause_msec ) void uniset_rwmutex::wrlock( int check_pause_msec )
{ {
wr_wait += 1; wr_wait += 1;
while( !m.tryWriteLock() ) while( !m.tryWriteLock() )
...@@ -179,8 +203,9 @@ void uniset_spin_mutex::wrlock( int check_pause_msec ) ...@@ -179,8 +203,9 @@ void uniset_spin_mutex::wrlock( int check_pause_msec )
msleep(check_pause_msec); msleep(check_pause_msec);
} }
wr_wait -= 1; wr_wait -= 1;
MUTEX_DEBUG(cerr << nm << " WRLocked.." << endl;)
} }
void uniset_spin_mutex::rlock( int check_pause_msec ) void uniset_rwmutex::rlock( int check_pause_msec )
{ {
while( wr_wait > 0 ) while( wr_wait > 0 )
msleep(check_pause_msec); msleep(check_pause_msec);
...@@ -190,42 +215,34 @@ void uniset_spin_mutex::rlock( int check_pause_msec ) ...@@ -190,42 +215,34 @@ void uniset_spin_mutex::rlock( int check_pause_msec )
if( check_pause_msec > 0 ) if( check_pause_msec > 0 )
msleep(check_pause_msec); msleep(check_pause_msec);
} }
}
void uniset_spin_mutex::unlock() MUTEX_DEBUG(cerr << nm << " RLocked.." << endl;)
{
m.unlock();
}
// -------------------------------------------------------------------------------------------
uniset_spin_lock::uniset_spin_lock( uniset_spin_mutex& _m, int check_pause_msec ):
m(_m)
{
m.lock(check_pause_msec);
} }
uniset_spin_lock::~uniset_spin_lock() void uniset_rwmutex::unlock()
{ {
m.unlock(); m.unlock();
MUTEX_DEBUG(cerr << nm << " Unlocked.." << endl;)
} }
// -------------------------------------------------------------------------------------------
uniset_spin_wrlock::uniset_spin_wrlock( uniset_spin_mutex& _m, int check_pause_msec ): uniset_rwmutex_wrlock::uniset_rwmutex_wrlock( uniset_rwmutex& _m, int check_pause_msec ):
uniset_spin_lock(_m) m(_m)
{ {
m.wrlock(check_pause_msec); m.wrlock(check_pause_msec);
} }
uniset_spin_wrlock::~uniset_spin_wrlock() uniset_rwmutex_wrlock::~uniset_rwmutex_wrlock()
{ {
// unlocked in uniset_spin_lock destructor m.unlock();
} }
uniset_spin_wrlock::uniset_spin_wrlock( const uniset_spin_wrlock& r ): uniset_rwmutex_wrlock::uniset_rwmutex_wrlock( const uniset_rwmutex_wrlock& r ):
uniset_spin_lock(r.m) m(r.m)
{ {
} }
uniset_spin_wrlock& uniset_spin_wrlock::operator=(const uniset_spin_wrlock& r) uniset_rwmutex_wrlock& uniset_rwmutex_wrlock::operator=(const uniset_rwmutex_wrlock& r)
{ {
if( this != &r ) if( this != &r )
m = r.m; m = r.m;
...@@ -233,31 +250,28 @@ uniset_spin_wrlock& uniset_spin_wrlock::operator=(const uniset_spin_wrlock& r) ...@@ -233,31 +250,28 @@ uniset_spin_wrlock& uniset_spin_wrlock::operator=(const uniset_spin_wrlock& r)
return *this; return *this;
} }
// ------------------------------------------------------------------------------------------- // -------------------------------------------------------------------------------------------
uniset_spin_rlock::uniset_spin_rlock( uniset_spin_mutex& _m, int check_pause_msec ): uniset_rwmutex_rlock::uniset_rwmutex_rlock( uniset_rwmutex& _m, int check_pause_msec ):
uniset_spin_lock(_m) m(_m)
{ {
m.rlock(check_pause_msec); m.rlock(check_pause_msec);
} }
uniset_spin_rlock::~uniset_spin_rlock() uniset_rwmutex_rlock::~uniset_rwmutex_rlock()
{ {
// unlocked in uniset_spin_lock destructor m.unlock();
} }
uniset_spin_rlock::uniset_spin_rlock( const uniset_spin_rlock& r ): uniset_rwmutex_rlock::uniset_rwmutex_rlock( const uniset_rwmutex_rlock& r ):
uniset_spin_lock(r.m) m(r.m)
{ {
} }
uniset_spin_rlock& uniset_spin_rlock::operator=(const uniset_spin_rlock& r) uniset_rwmutex_rlock& uniset_rwmutex_rlock::operator=(const uniset_rwmutex_rlock& r)
{ {
if( this != &r ) if( this != &r )
m = r.m; m = r.m;
return *this; return *this;
} }
// -----------------------------------------------------------------------------
#undef MUTEX_LOCK_SLEEP_MS
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
#include <string>
#include <sstream>
#include "Mutex.h"
#include "ThreadCreator.h"
#include "UniSetTypes.h"
#include "modbus/TCPCheck.h"
using namespace std;
using namespace UniSetTypes;
const string ip1="localhost:2049";
const string ip2="localhost:2048";
const string ip3="192.168.77.11:2049";
uniset_mutex m;
class MyClass
{
public:
MyClass( const std::string& name ): nm(name)
{
thr = new ThreadCreator<MyClass>(this, &MyClass::thread);
}
~MyClass()
{
delete thr;
}
inline cctid_t start(){ return thr->start(); }
inline void stop(){ thr->stop(); }
inline pid_t getTID(){ return thr->getTID(); }
// BAD code...only for tests
inline ThreadCreator<MyClass>* mythr(){ return thr; }
protected:
std::string nm;
void thread()
{
cout << nm << ": start thread (" << getTID() << ")" << endl;
while(1)
{
ost::Thread::sleep(10000);
}
cout << nm << ": finish thread (" << getTID() << ")" << endl;
}
private:
ThreadCreator<MyClass>* thr;
};
class MyClass2
{
public:
MyClass2( const std::string& name ): nm(name)
{
thr = new ThreadCreator<MyClass2>(this, &MyClass2::thread);
}
~MyClass2(){ delete thr; }
inline cctid_t start(){ return thr->start(); }
inline void stop(){ thr->stop(); }
inline pid_t getTID(){ return thr->getTID(); }
protected:
std::string nm;
TCPCheck tcp;
void thread()
{
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
cout << nm << ": start thread (" << getTID() << ")" << endl;
while(1)
{
cout << nm << " check " << ip1 << ": " << ( tcp.check(ip1,300,100) ? "OK" : "FAIL" ) << endl;
pthread_testcancel();
cout << nm << " check " << ip2 << ": " << ( tcp.check(ip2,300,100) ? "OK" : "FAIL" ) << endl;
pthread_testcancel();
cout << nm << " check " << ip3 << ": " << ( tcp.check(ip3,300,100) ? "OK" : "FAIL" ) << endl;
pthread_testcancel();
cout << nm << " msleep 2000" << endl;
ost::Thread::sleep(2000);
pthread_testcancel();
}
cout << nm << ": finish thread (" << getTID() << ")" << endl;
}
private:
ThreadCreator<MyClass2>* thr;
};
int main( int argc, const char **argv )
{
try
{
MyClass t1("Thread1");
cout << "start1..." << endl;
t1.start();
msleep(30);
cout << "TID: " << t1.getTID() << endl;
msleep(500);
cout << "stop1..." << endl;
t1.stop();
msleep(100);
cout << "start2..." << endl;
t1.start();
int prior = t1.mythr()->getPriority();
cout << "priority: " << prior << endl;
cout << "set prior +1 [" << prior++ << "]" << endl;
t1.mythr()->setPriority(prior);
cout << "check priority: " << t1.mythr()->getPriority() << endl;
prior=-2;
cout << "set prior -2 " << endl;
cout << "retcode=" << t1.mythr()->setPriority(prior) << endl;
cout << "check priority: " << t1.mythr()->getPriority() << endl;
msleep(500);
// cout << "kill2..." << endl;
// t1.kill(SIGUSR1);
// msleep(100);
// cout << "start3..." << endl;
// t1.start();
// pause();
cout << "finished3..." << endl;
TCPCheck tcp;
cout << "check " << ip1 << ": " << ( tcp.check(ip1,300,100) ? "OK" : "FAIL" ) << endl;
cout << "check " << ip2 << ": " << ( tcp.check(ip2,300,100) ? "OK" : "FAIL" ) << endl;
cout << "check " << ip3 << ": " << ( tcp.check(ip3,300,100) ? "OK" : "FAIL" ) << endl;
msleep(50);
cout << "check finished..." << endl;
// поток в потоке..
MyClass2 t2("Thread2");
cout << "thread2 start..." << endl;
t2.start();
msleep(6000);
cout << "thread2 stop..." << endl;
t2.stop();
}
catch( std::exception& ex )
{
cerr << "catch: " << ex.what() << endl;
}
return 0;
}
...@@ -9,7 +9,7 @@ using namespace std; ...@@ -9,7 +9,7 @@ using namespace std;
using namespace UniSetTypes; using namespace UniSetTypes;
uniset_mutex m; uniset_mutex m;
uniset_spin_mutex m_spin; uniset_rwmutex m_spin;
class MyClass class MyClass
{ {
...@@ -89,7 +89,7 @@ class MyClassSpin ...@@ -89,7 +89,7 @@ class MyClassSpin
if( !readLock ) if( !readLock )
{ {
// cerr << nm << ": before RWlock.." << endl; // cerr << nm << ": before RWlock.." << endl;
uniset_spin_lock l(m_spin,5); uniset_rwmutex_wrlock l(m_spin,5);
count++; count++;
msleep(30); msleep(30);
// cerr << nm << ": after RWlock.." << endl; // cerr << nm << ": after RWlock.." << endl;
...@@ -97,7 +97,7 @@ class MyClassSpin ...@@ -97,7 +97,7 @@ class MyClassSpin
else else
{ {
// cerr << nm << "(readLock): before lock.." << endl; // cerr << nm << "(readLock): before lock.." << endl;
uniset_spin_rlock l(m_spin); uniset_rwmutex_rlock l(m_spin);
count++; count++;
msleep(20); msleep(20);
// cerr << nm << "(readLock): after lock.." << endl; // cerr << nm << "(readLock): after lock.." << endl;
...@@ -160,8 +160,8 @@ int main( int argc, const char **argv ) ...@@ -160,8 +160,8 @@ int main( int argc, const char **argv )
cerr << "test write lock: " << (check_wr_lock(m) ? "FAIL" : "OK [0]") << endl; cerr << "test write lock: " << (check_wr_lock(m) ? "FAIL" : "OK [0]") << endl;
cerr << "test read lock: " << (check_r_lock(m) ? "FAIL" : "OK [0]") << endl; cerr << "test read lock: " << (check_r_lock(m) ? "FAIL" : "OK [0]") << endl;
cerr << endl << "***** uniset_spin_mutex ***" << endl; cerr << endl << "***** uniset_rwmutex ***" << endl;
uniset_spin_mutex m1; uniset_rwmutex m1;
cout << "read lock.." << endl; cout << "read lock.." << endl;
m1.rlock(); m1.rlock();
......
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