From 0fa3a4923efb492a71f888e256348148fdd73d80 Mon Sep 17 00:00:00 2001 From: leak Date: Mon, 2 Jun 2014 23:01:01 +0200 Subject: Replaced LockedQueue ACE lock with std::mutex --- src/server/shared/Common.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/server/shared/Common.h') diff --git a/src/server/shared/Common.h b/src/server/shared/Common.h index f49bbf0bada..14cc6533a68 100644 --- a/src/server/shared/Common.h +++ b/src/server/shared/Common.h @@ -79,10 +79,11 @@ #include #include +#include "Debugging/Errors.h" + #include "Threading/LockedQueue.h" #include "Threading/Threading.h" -#include #include #include #include -- cgit v1.2.3 From ee4a3b9d59867a2440f8eb35f96405e5c4f6fe28 Mon Sep 17 00:00:00 2001 From: leak Date: Sun, 8 Jun 2014 15:30:57 +0200 Subject: Replaced mutex related code in Common.h --- src/server/collision/Management/VMapManager2.cpp | 5 ++- src/server/collision/Management/VMapManager2.h | 6 +-- src/server/game/Events/GameEventMgr.cpp | 4 +- src/server/game/Globals/ObjectAccessor.cpp | 23 ++++++---- src/server/game/Globals/ObjectAccessor.h | 53 +++++++++++++----------- src/server/game/Handlers/MiscHandler.cpp | 3 +- src/server/game/Instances/InstanceSaveMgr.h | 28 +++++++++---- src/server/game/Maps/Map.cpp | 6 +-- src/server/game/Maps/Map.h | 4 +- src/server/game/Maps/MapInstanced.cpp | 4 +- src/server/game/Maps/MapManager.cpp | 6 +-- src/server/game/Maps/MapManager.h | 2 +- src/server/game/Maps/MapUpdater.cpp | 39 +++++++++++++---- src/server/game/Maps/MapUpdater.h | 26 ++++++++++-- src/server/game/Server/WorldSocketMgr.cpp | 8 ++-- src/server/scripts/Commands/cs_gm.cpp | 2 +- src/server/scripts/Commands/cs_reset.cpp | 2 +- src/server/shared/Common.h | 19 --------- src/server/shared/Threading/LockedQueue.h | 2 - 19 files changed, 142 insertions(+), 100 deletions(-) (limited to 'src/server/shared/Common.h') diff --git a/src/server/collision/Management/VMapManager2.cpp b/src/server/collision/Management/VMapManager2.cpp index 813a3c04288..2aa3b6ab40d 100644 --- a/src/server/collision/Management/VMapManager2.cpp +++ b/src/server/collision/Management/VMapManager2.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include "VMapManager2.h" @@ -252,7 +253,7 @@ namespace VMAP WorldModel* VMapManager2::acquireModelInstance(const std::string& basepath, const std::string& filename) { //! Critical section, thread safe access to iLoadedModelFiles - TRINITY_GUARD(ACE_Thread_Mutex, LoadedModelFilesLock); + std::lock_guard lock(LoadedModelFilesLock); ModelFileMap::iterator model = iLoadedModelFiles.find(filename); if (model == iLoadedModelFiles.end()) @@ -275,7 +276,7 @@ namespace VMAP void VMapManager2::releaseModelInstance(const std::string &filename) { //! Critical section, thread safe access to iLoadedModelFiles - TRINITY_GUARD(ACE_Thread_Mutex, LoadedModelFilesLock); + std::lock_guard lock(LoadedModelFilesLock); ModelFileMap::iterator model = iLoadedModelFiles.find(filename); if (model == iLoadedModelFiles.end()) diff --git a/src/server/collision/Management/VMapManager2.h b/src/server/collision/Management/VMapManager2.h index 711025e67c0..03de6951d5d 100644 --- a/src/server/collision/Management/VMapManager2.h +++ b/src/server/collision/Management/VMapManager2.h @@ -19,10 +19,10 @@ #ifndef _VMAPMANAGER2_H #define _VMAPMANAGER2_H +#include +#include #include "Define.h" #include "IVMapManager.h" -#include -#include //=========================================================== @@ -73,7 +73,7 @@ namespace VMAP ModelFileMap iLoadedModelFiles; InstanceTreeMap iInstanceMapTrees; // Mutex for iLoadedModelFiles - ACE_Thread_Mutex LoadedModelFilesLock; + std::mutex LoadedModelFilesLock; bool _loadMap(uint32 mapId, const std::string& basePath, uint32 tileX, uint32 tileY); /* void _unloadMap(uint32 pMapId, uint32 x, uint32 y); */ diff --git a/src/server/game/Events/GameEventMgr.cpp b/src/server/game/Events/GameEventMgr.cpp index 5669f36a939..9e1514f11bd 100644 --- a/src/server/game/Events/GameEventMgr.cpp +++ b/src/server/game/Events/GameEventMgr.cpp @@ -1600,14 +1600,14 @@ void GameEventMgr::RunSmartAIScripts(uint16 event_id, bool activate) //! Iterate over every supported source type (creature and gameobject) //! Not entirely sure how this will affect units in non-loaded grids. { - TRINITY_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); + boost::shared_lock lock(*HashMapHolder::GetLock()); HashMapHolder::MapType const& m = ObjectAccessor::GetCreatures(); for (HashMapHolder::MapType::const_iterator iter = m.begin(); iter != m.end(); ++iter) if (iter->second->IsInWorld()) iter->second->AI()->sOnGameEvent(activate, event_id); } { - TRINITY_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); + boost::shared_lock lock(*HashMapHolder::GetLock()); HashMapHolder::MapType const& m = ObjectAccessor::GetGameObjects(); for (HashMapHolder::MapType::const_iterator iter = m.begin(); iter != m.end(); ++iter) if (iter->second->IsInWorld()) diff --git a/src/server/game/Globals/ObjectAccessor.cpp b/src/server/game/Globals/ObjectAccessor.cpp index 8bf353d3eaa..ec33d8efbe1 100644 --- a/src/server/game/Globals/ObjectAccessor.cpp +++ b/src/server/game/Globals/ObjectAccessor.cpp @@ -16,6 +16,9 @@ * with this program. If not, see . */ +#include +#include + #include "ObjectAccessor.h" #include "CellImpl.h" #include "Corpse.h" @@ -205,7 +208,8 @@ Unit* ObjectAccessor::FindUnit(uint64 guid) Player* ObjectAccessor::FindPlayerByName(std::string const& name) { - TRINITY_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); + boost::shared_lock lock(*HashMapHolder::GetLock()); + std::string nameStr = name; std::transform(nameStr.begin(), nameStr.end(), nameStr.begin(), ::tolower); HashMapHolder::MapType const& m = GetPlayers(); @@ -224,7 +228,8 @@ Player* ObjectAccessor::FindPlayerByName(std::string const& name) void ObjectAccessor::SaveAllPlayers() { - TRINITY_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); + boost::shared_lock lock(*HashMapHolder::GetLock()); + HashMapHolder::MapType const& m = GetPlayers(); for (HashMapHolder::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) itr->second->SaveToDB(); @@ -232,7 +237,7 @@ void ObjectAccessor::SaveAllPlayers() Corpse* ObjectAccessor::GetCorpseForPlayerGUID(uint64 guid) { - TRINITY_READ_GUARD(ACE_RW_Thread_Mutex, i_corpseLock); + boost::shared_lock lock(_corpseLock); Player2CorpsesMapType::iterator iter = i_player2corpse.find(guid); if (iter == i_player2corpse.end()) @@ -247,6 +252,8 @@ void ObjectAccessor::RemoveCorpse(Corpse* corpse) { ASSERT(corpse && corpse->GetType() != CORPSE_BONES); + boost::upgrade_lock lock(_corpseLock); + /// @todo more works need to be done for corpse and other world object if (Map* map = corpse->FindMap()) { @@ -265,7 +272,7 @@ void ObjectAccessor::RemoveCorpse(Corpse* corpse) // Critical section { - TRINITY_WRITE_GUARD(ACE_RW_Thread_Mutex, i_corpseLock); + boost::upgrade_to_unique_lock uniqueLock(lock); Player2CorpsesMapType::iterator iter = i_player2corpse.find(corpse->GetOwnerGUID()); if (iter == i_player2corpse.end()) /// @todo Fix this @@ -285,7 +292,7 @@ void ObjectAccessor::AddCorpse(Corpse* corpse) // Critical section { - TRINITY_WRITE_GUARD(ACE_RW_Thread_Mutex, i_corpseLock); + boost::unique_lock lock(_corpseLock); ASSERT(i_player2corpse.find(corpse->GetOwnerGUID()) == i_player2corpse.end()); i_player2corpse[corpse->GetOwnerGUID()] = corpse; @@ -298,7 +305,7 @@ void ObjectAccessor::AddCorpse(Corpse* corpse) void ObjectAccessor::AddCorpsesToGrid(GridCoord const& gridpair, GridType& grid, Map* map) { - TRINITY_READ_GUARD(ACE_RW_Thread_Mutex, i_corpseLock); + boost::shared_lock lock(_corpseLock); for (Player2CorpsesMapType::iterator iter = i_player2corpse.begin(); iter != i_player2corpse.end(); ++iter) { @@ -431,8 +438,8 @@ void ObjectAccessor::UnloadAll() /// Define the static members of HashMapHolder -template std::unordered_map< uint64, T* > HashMapHolder::m_objectMap; -template typename HashMapHolder::LockType HashMapHolder::i_lock; +template std::unordered_map< uint64, T* > HashMapHolder::_objectMap; +template boost::shared_mutex HashMapHolder::_lock; /// Global definitions for the hashmap storage diff --git a/src/server/game/Globals/ObjectAccessor.h b/src/server/game/Globals/ObjectAccessor.h index b52699c85ac..79799cec55f 100644 --- a/src/server/game/Globals/ObjectAccessor.h +++ b/src/server/game/Globals/ObjectAccessor.h @@ -19,17 +19,17 @@ #ifndef TRINITY_OBJECTACCESSOR_H #define TRINITY_OBJECTACCESSOR_H -#include "Define.h" -#include -#include +#include +#include #include +#include +#include -#include "UpdateData.h" - +#include "Define.h" #include "GridDefines.h" +#include "UpdateData.h" #include "Object.h" -#include class Creature; class Corpse; @@ -48,42 +48,41 @@ class HashMapHolder public: typedef std::unordered_map MapType; - typedef ACE_RW_Thread_Mutex LockType; static void Insert(T* o) { - TRINITY_WRITE_GUARD(LockType, i_lock); - m_objectMap[o->GetGUID()] = o; + boost::shared_lock lock(_lock); + + _objectMap[o->GetGUID()] = o; } static void Remove(T* o) { - TRINITY_WRITE_GUARD(LockType, i_lock); - m_objectMap.erase(o->GetGUID()); + boost::unique_lock lock(_lock); + _objectMap.erase(o->GetGUID()); } static T* Find(uint64 guid) { - TRINITY_READ_GUARD(LockType, i_lock); - typename MapType::iterator itr = m_objectMap.find(guid); - return (itr != m_objectMap.end()) ? itr->second : NULL; + boost::shared_lock lock(_lock); + typename MapType::iterator itr = _objectMap.find(guid); + return (itr != _objectMap.end()) ? itr->second : NULL; } - static MapType& GetContainer() { return m_objectMap; } + static MapType& GetContainer() { return _objectMap; } - static LockType* GetLock() { return &i_lock; } + static boost::shared_mutex* GetLock() { return &_lock; } private: //Non instanceable only static HashMapHolder() { } - static LockType i_lock; - static MapType m_objectMap; + static boost::shared_mutex _lock; + static MapType _objectMap; }; class ObjectAccessor { - friend class ACE_Singleton; private: ObjectAccessor(); ~ObjectAccessor(); @@ -93,6 +92,12 @@ class ObjectAccessor public: /// @todo: Override these template functions for each holder type and add assertions + static ObjectAccessor* instance() + { + static ObjectAccessor *instance = new ObjectAccessor(); + return instance; + } + template static T* GetObjectInOrOutOfWorld(uint64 guid, T* /*typeSpecifier*/) { return HashMapHolder::Find(guid); @@ -195,13 +200,13 @@ class ObjectAccessor //non-static functions void AddUpdateObject(Object* obj) { - TRINITY_GUARD(ACE_Thread_Mutex, i_objectLock); + std::lock_guard lock(_objectLock); i_objects.insert(obj); } void RemoveUpdateObject(Object* obj) { - TRINITY_GUARD(ACE_Thread_Mutex, i_objectLock); + std::lock_guard lock(_objectLock); i_objects.erase(obj); } @@ -228,9 +233,9 @@ class ObjectAccessor std::set i_objects; Player2CorpsesMapType i_player2corpse; - ACE_Thread_Mutex i_objectLock; - ACE_RW_Thread_Mutex i_corpseLock; + std::mutex _objectLock; + boost::shared_mutex _corpseLock; }; -#define sObjectAccessor ACE_Singleton::instance() +#define sObjectAccessor ObjectAccessor::instance() #endif diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index 1b04c89b338..40830d63d05 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -260,7 +260,8 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recvData) data << uint32(matchcount); // placeholder, count of players matching criteria data << uint32(displaycount); // placeholder, count of players displayed - TRINITY_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); + boost::shared_lock lock(*HashMapHolder::GetLock()); + HashMapHolder::MapType const& m = sObjectAccessor->GetPlayers(); for (HashMapHolder::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) { diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h index 4f1b576cae6..98b37386a3f 100644 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ b/src/server/game/Instances/InstanceSaveMgr.h @@ -19,12 +19,12 @@ #ifndef _INSTANCESAVEMGR_H #define _INSTANCESAVEMGR_H -#include "Define.h" -#include -#include #include #include +#include #include + +#include "Define.h" #include "DatabaseEnv.h" #include "DBCEnums.h" #include "ObjectDefines.h" @@ -80,13 +80,18 @@ class InstanceSave /* online players bound to the instance (perm/solo) does not include the members of the group unless they have permanent saves */ - void AddPlayer(Player* player) { TRINITY_GUARD(ACE_Thread_Mutex, _lock); m_playerList.push_back(player); } + void AddPlayer(Player* player) + { + std::lock_guard lock(_playerListLock); + m_playerList.push_back(player); + } + bool RemovePlayer(Player* player) { - _lock.acquire(); + _playerListLock.lock(); m_playerList.remove(player); bool isStillValid = UnloadIfEmpty(); - _lock.release(); + _playerListLock.unlock(); //delete here if needed, after releasing the lock if (m_toDelete) @@ -137,14 +142,13 @@ class InstanceSave bool m_canReset; bool m_toDelete; - ACE_Thread_Mutex _lock; + std::mutex _playerListLock; }; typedef std::unordered_map ResetTimeByMapDifficultyMap; class InstanceSaveManager { - friend class ACE_Singleton; friend class InstanceSave; private: @@ -154,6 +158,12 @@ class InstanceSaveManager public: typedef std::unordered_map InstanceSaveHashMap; + static InstanceSaveManager* instance() + { + static InstanceSaveManager *instance = new InstanceSaveManager(); + return instance; + } + /* resetTime is a global propery of each (raid/heroic) map all instances of that map reset at the same time */ struct InstResetEvent @@ -221,5 +231,5 @@ class InstanceSaveManager ResetTimeQueue m_resetTimeQueue; }; -#define sInstanceSaveMgr ACE_Singleton::instance() +#define sInstanceSaveMgr InstanceSaveManager::instance() #endif diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index ba271235330..96c784cc9d9 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -382,7 +382,7 @@ void Map::DeleteFromWorld(Player* player) void Map::EnsureGridCreated(const GridCoord &p) { - TRINITY_GUARD(ACE_Thread_Mutex, GridLock); + std::lock_guard lock(_gridLock); EnsureGridCreated_i(p); } @@ -2901,7 +2901,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) // Is it needed? { - TRINITY_GUARD(ACE_Thread_Mutex, Lock); + std::lock_guard lock(_mapLock); // Check moved to void WorldSession::HandleMoveWorldportAckOpcode() //if (!CanEnter(player)) //return false; @@ -3242,7 +3242,7 @@ bool BattlegroundMap::CanEnter(Player* player) bool BattlegroundMap::AddPlayerToMap(Player* player) { { - TRINITY_GUARD(ACE_Thread_Mutex, Lock); + std::lock_guard lock(_mapLock); //Check moved to void WorldSession::HandleMoveWorldportAckOpcode() //if (!CanEnter(player)) //return false; diff --git a/src/server/game/Maps/Map.h b/src/server/game/Maps/Map.h index a2d88905f50..27c290264b2 100644 --- a/src/server/game/Maps/Map.h +++ b/src/server/game/Maps/Map.h @@ -574,8 +574,8 @@ class Map : public GridRefManager protected: void SetUnloadReferenceLock(const GridCoord &p, bool on) { getNGrid(p.x_coord, p.y_coord)->setUnloadReferenceLock(on); } - ACE_Thread_Mutex Lock; - ACE_Thread_Mutex GridLock; + std::mutex _mapLock; + std::mutex _gridLock; MapEntry const* i_mapEntry; uint8 i_spawnMode; diff --git a/src/server/game/Maps/MapInstanced.cpp b/src/server/game/Maps/MapInstanced.cpp index e914a5c3eee..498c669ba01 100644 --- a/src/server/game/Maps/MapInstanced.cpp +++ b/src/server/game/Maps/MapInstanced.cpp @@ -187,7 +187,7 @@ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player) InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, Difficulty difficulty) { // load/create a map - TRINITY_GUARD(ACE_Thread_Mutex, Lock); + std::lock_guard lock(_mapLock); // make sure we have a valid map id const MapEntry* entry = sMapStore.LookupEntry(GetId()); @@ -223,7 +223,7 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, BattlegroundMap* MapInstanced::CreateBattleground(uint32 InstanceId, Battleground* bg) { // load/create a map - TRINITY_GUARD(ACE_Thread_Mutex, Lock); + std::lock_guard lock(_mapLock); TC_LOG_DEBUG("maps", "MapInstanced::CreateBattleground: map bg %d for %d created.", InstanceId, GetId()); diff --git a/src/server/game/Maps/MapManager.cpp b/src/server/game/Maps/MapManager.cpp index d8c8889da67..2b8dbde8280 100644 --- a/src/server/game/Maps/MapManager.cpp +++ b/src/server/game/Maps/MapManager.cpp @@ -68,7 +68,7 @@ Map* MapManager::CreateBaseMap(uint32 id) if (map == NULL) { - TRINITY_GUARD(ACE_Thread_Mutex, Lock); + std::lock_guard lock(_mapsLock); MapEntry const* entry = sMapStore.LookupEntry(id); ASSERT(entry); @@ -302,7 +302,7 @@ void MapManager::UnloadAll() uint32 MapManager::GetNumInstances() { - TRINITY_GUARD(ACE_Thread_Mutex, Lock); + std::lock_guard lock(_mapsLock); uint32 ret = 0; for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr) @@ -319,7 +319,7 @@ uint32 MapManager::GetNumInstances() uint32 MapManager::GetNumPlayersInInstances() { - TRINITY_GUARD(ACE_Thread_Mutex, Lock); + std::lock_guard lock(_mapsLock); uint32 ret = 0; for (MapMapType::iterator itr = i_maps.begin(); itr != i_maps.end(); ++itr) diff --git a/src/server/game/Maps/MapManager.h b/src/server/game/Maps/MapManager.h index b7fb0617a46..91becb88dfe 100644 --- a/src/server/game/Maps/MapManager.h +++ b/src/server/game/Maps/MapManager.h @@ -141,7 +141,7 @@ class MapManager MapManager(const MapManager &); MapManager& operator=(const MapManager &); - ACE_Thread_Mutex Lock; + std::mutex _mapsLock; uint32 i_gridCleanUpDelay; MapMapType i_maps; IntervalTimer i_timer; diff --git a/src/server/game/Maps/MapUpdater.cpp b/src/server/game/Maps/MapUpdater.cpp index f3a5a66bf66..c2d8123c2d2 100644 --- a/src/server/game/Maps/MapUpdater.cpp +++ b/src/server/game/Maps/MapUpdater.cpp @@ -1,10 +1,30 @@ +/* +* Copyright (C) 2008-2014 TrinityCore +* Copyright (C) 2005-2009 MaNGOS +* +* 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, see . +*/ + +#include +#include +#include + #include "MapUpdater.h" #include "DelayExecutor.h" #include "Map.h" #include "DatabaseEnv.h" -#include -#include class WDBThreadStartReq1 : public ACE_Method_Request { @@ -57,8 +77,7 @@ class MapUpdateRequest : public ACE_Method_Request } }; -MapUpdater::MapUpdater(): -m_executor(), m_mutex(), m_condition(m_mutex), pending_requests(0) { } +MapUpdater::MapUpdater(): m_executor(), pending_requests(0) { } MapUpdater::~MapUpdater() { @@ -79,17 +98,19 @@ int MapUpdater::deactivate() int MapUpdater::wait() { - TRINITY_GUARD(ACE_Thread_Mutex, m_mutex); + std::unique_lock lock(_lock); while (pending_requests > 0) - m_condition.wait(); + _condition.wait(lock); + + lock.unlock(); return 0; } int MapUpdater::schedule_update(Map& map, ACE_UINT32 diff) { - TRINITY_GUARD(ACE_Thread_Mutex, m_mutex); + std::lock_guard lock(_lock); ++pending_requests; @@ -111,7 +132,7 @@ bool MapUpdater::activated() void MapUpdater::update_finished() { - TRINITY_GUARD(ACE_Thread_Mutex, m_mutex); + std::lock_guard lock(_lock); if (pending_requests == 0) { @@ -121,5 +142,5 @@ void MapUpdater::update_finished() --pending_requests; - m_condition.broadcast(); + _condition.notify_all(); } diff --git a/src/server/game/Maps/MapUpdater.h b/src/server/game/Maps/MapUpdater.h index 89798026339..8461b53e992 100644 --- a/src/server/game/Maps/MapUpdater.h +++ b/src/server/game/Maps/MapUpdater.h @@ -1,8 +1,26 @@ +/* +* Copyright (C) 2008-2014 TrinityCore +* Copyright (C) 2005-2009 MaNGOS +* +* 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, see . +*/ + #ifndef _MAP_UPDATER_H_INCLUDED #define _MAP_UPDATER_H_INCLUDED -#include -#include +#include +#include #include "DelayExecutor.h" @@ -30,8 +48,8 @@ class MapUpdater private: DelayExecutor m_executor; - ACE_Thread_Mutex m_mutex; - ACE_Condition_Thread_Mutex m_condition; + std::mutex _lock; + std::condition_variable _condition; size_t pending_requests; void update_finished(); diff --git a/src/server/game/Server/WorldSocketMgr.cpp b/src/server/game/Server/WorldSocketMgr.cpp index 7880552ffa1..3c1db3551d0 100644 --- a/src/server/game/Server/WorldSocketMgr.cpp +++ b/src/server/game/Server/WorldSocketMgr.cpp @@ -29,13 +29,13 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include "Log.h" @@ -109,7 +109,7 @@ class ReactorRunnable : protected ACE_Task_Base int AddSocket (WorldSocket* sock) { - TRINITY_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock); + std::lock_guard lock(newSocketsLock); ++m_Connections; sock->AddReference(); @@ -130,7 +130,7 @@ class ReactorRunnable : protected ACE_Task_Base void AddNewSockets() { - TRINITY_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock); + std::lock_guard lock(newSocketsLock); if (m_NewSockets.empty()) return; @@ -208,7 +208,7 @@ class ReactorRunnable : protected ACE_Task_Base SocketSet m_Sockets; SocketSet m_NewSockets; - ACE_Thread_Mutex m_NewSockets_Lock; + std::mutex newSocketsLock; }; WorldSocketMgr::WorldSocketMgr() : diff --git a/src/server/scripts/Commands/cs_gm.cpp b/src/server/scripts/Commands/cs_gm.cpp index a2c0861c113..90fd0bdd71c 100644 --- a/src/server/scripts/Commands/cs_gm.cpp +++ b/src/server/scripts/Commands/cs_gm.cpp @@ -123,7 +123,7 @@ public: bool first = true; bool footer = false; - TRINITY_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); + boost::shared_lock lock(*HashMapHolder::GetLock()); HashMapHolder::MapType const& m = sObjectAccessor->GetPlayers(); for (HashMapHolder::MapType::const_iterator itr = m.begin(); itr != m.end(); ++itr) { diff --git a/src/server/scripts/Commands/cs_reset.cpp b/src/server/scripts/Commands/cs_reset.cpp index d61c36c887f..279f9c2ef4c 100644 --- a/src/server/scripts/Commands/cs_reset.cpp +++ b/src/server/scripts/Commands/cs_reset.cpp @@ -297,7 +297,7 @@ public: stmt->setUInt16(0, uint16(atLogin)); CharacterDatabase.Execute(stmt); - TRINITY_READ_GUARD(HashMapHolder::LockType, *HashMapHolder::GetLock()); + boost::shared_lock lock(*HashMapHolder::GetLock()); HashMapHolder::MapType const& plist = sObjectAccessor->GetPlayers(); for (HashMapHolder::MapType::const_iterator itr = plist.begin(); itr != plist.end(); ++itr) itr->second->SetAtLoginFlag(atLogin); diff --git a/src/server/shared/Common.h b/src/server/shared/Common.h index 14cc6533a68..a7bc3acd1e5 100644 --- a/src/server/shared/Common.h +++ b/src/server/shared/Common.h @@ -84,9 +84,6 @@ #include "Threading/LockedQueue.h" #include "Threading/Threading.h" -#include -#include -#include #include #if PLATFORM == PLATFORM_WINDOWS @@ -188,20 +185,4 @@ typedef std::vector StringVector; #define MAX_QUERY_LEN 32*1024 -#define TRINITY_GUARD(MUTEX, LOCK) \ - ACE_Guard< MUTEX > TRINITY_GUARD_OBJECT (LOCK); \ - if (TRINITY_GUARD_OBJECT.locked() == 0) ASSERT(false); - -//! For proper implementation of multiple-read, single-write pattern, use -//! ACE_RW_Mutex as underlying @MUTEX -# define TRINITY_WRITE_GUARD(MUTEX, LOCK) \ - ACE_Write_Guard< MUTEX > TRINITY_GUARD_OBJECT (LOCK); \ - if (TRINITY_GUARD_OBJECT.locked() == 0) ASSERT(false); - -//! For proper implementation of multiple-read, single-write pattern, use -//! ACE_RW_Mutex as underlying @MUTEX -# define TRINITY_READ_GUARD(MUTEX, LOCK) \ - ACE_Read_Guard< MUTEX > TRINITY_GUARD_OBJECT (LOCK); \ - if (TRINITY_GUARD_OBJECT.locked() == 0) ASSERT(false); - #endif diff --git a/src/server/shared/Threading/LockedQueue.h b/src/server/shared/Threading/LockedQueue.h index 3ca2a5cd45c..93225496df3 100644 --- a/src/server/shared/Threading/LockedQueue.h +++ b/src/server/shared/Threading/LockedQueue.h @@ -22,8 +22,6 @@ #include #include - - template > class LockedQueue { -- cgit v1.2.3 From 0dd10269d15b11b3beb0cb1b8537e15126699d32 Mon Sep 17 00:00:00 2001 From: leak Date: Sun, 8 Jun 2014 20:08:43 +0200 Subject: Replaced dependencies on ace/OS_NS_time.h --- src/server/shared/Common.h | 2 - src/server/shared/Logging/Appender.cpp | 4 +- src/server/shared/Logging/Log.cpp | 7 +- src/server/shared/Utilities/Timer.h | 248 +++++++++++++++++---------------- src/server/shared/Utilities/Util.cpp | 15 +- src/server/shared/Utilities/Util.h | 2 + 6 files changed, 146 insertions(+), 132 deletions(-) (limited to 'src/server/shared/Common.h') diff --git a/src/server/shared/Common.h b/src/server/shared/Common.h index a7bc3acd1e5..54c7bfc5be8 100644 --- a/src/server/shared/Common.h +++ b/src/server/shared/Common.h @@ -84,8 +84,6 @@ #include "Threading/LockedQueue.h" #include "Threading/Threading.h" -#include - #if PLATFORM == PLATFORM_WINDOWS # include // XP winver - needed to compile with standard leak check in MemoryLeaks.h diff --git a/src/server/shared/Logging/Appender.cpp b/src/server/shared/Logging/Appender.cpp index 718c3a406f1..a4fc93e119c 100644 --- a/src/server/shared/Logging/Appender.cpp +++ b/src/server/shared/Logging/Appender.cpp @@ -17,11 +17,11 @@ #include "Appender.h" #include "Common.h" +#include "Util.h" std::string LogMessage::getTimeStr(time_t time) { - tm aTm; - ACE_OS::localtime_r(&time, &aTm); + tm aTm = localtime_r(time); char buf[20]; snprintf(buf, 20, "%04d-%02d-%02d_%02d:%02d:%02d", aTm.tm_year+1900, aTm.tm_mon+1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); return std::string(buf); diff --git a/src/server/shared/Logging/Log.cpp b/src/server/shared/Logging/Log.cpp index bc002668b3b..bb8cb1719c8 100644 --- a/src/server/shared/Logging/Log.cpp +++ b/src/server/shared/Logging/Log.cpp @@ -283,9 +283,10 @@ void Log::write(LogMessage* msg) std::string Log::GetTimestampStr() { - time_t t = time(NULL); - tm aTm; - ACE_OS::localtime_r(&t, &aTm); + time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + + std::tm aTm = localtime_r(tt); + // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) diff --git a/src/server/shared/Utilities/Timer.h b/src/server/shared/Utilities/Timer.h index c809a59c20f..7c62de5f5ed 100644 --- a/src/server/shared/Utilities/Timer.h +++ b/src/server/shared/Utilities/Timer.h @@ -19,13 +19,15 @@ #ifndef TRINITY_TIMER_H #define TRINITY_TIMER_H -#include "ace/OS_NS_sys_time.h" -#include "Common.h" +#include + +using namespace std::chrono; inline uint32 getMSTime() { - static const ACE_Time_Value ApplicationStartTime = ACE_OS::gettimeofday(); - return (ACE_OS::gettimeofday() - ApplicationStartTime).msec(); + static const system_clock::time_point ApplicationStartTime = system_clock::now(); + + return duration_cast(system_clock::now() - ApplicationStartTime).count(); } inline uint32 getMSTimeDiff(uint32 oldMSTime, uint32 newMSTime) @@ -44,158 +46,158 @@ inline uint32 GetMSTimeDiffToNow(uint32 oldMSTime) struct IntervalTimer { - public: - - IntervalTimer() - : _interval(0), _current(0) - { - } - - void Update(time_t diff) - { - _current += diff; - if (_current < 0) - _current = 0; - } - - bool Passed() - { - return _current >= _interval; - } - - void Reset() - { - if (_current >= _interval) - _current %= _interval; - } - - void SetCurrent(time_t current) - { - _current = current; - } - - void SetInterval(time_t interval) - { - _interval = interval; - } - - time_t GetInterval() const - { - return _interval; - } - - time_t GetCurrent() const - { - return _current; - } - - private: - - time_t _interval; - time_t _current; +public: + + IntervalTimer() + : _interval(0), _current(0) + { + } + + void Update(time_t diff) + { + _current += diff; + if (_current < 0) + _current = 0; + } + + bool Passed() + { + return _current >= _interval; + } + + void Reset() + { + if (_current >= _interval) + _current %= _interval; + } + + void SetCurrent(time_t current) + { + _current = current; + } + + void SetInterval(time_t interval) + { + _interval = interval; + } + + time_t GetInterval() const + { + return _interval; + } + + time_t GetCurrent() const + { + return _current; + } + +private: + + time_t _interval; + time_t _current; }; struct TimeTracker { - public: +public: - TimeTracker(time_t expiry) - : i_expiryTime(expiry) - { - } + TimeTracker(time_t expiry) + : i_expiryTime(expiry) + { + } - void Update(time_t diff) - { - i_expiryTime -= diff; - } + void Update(time_t diff) + { + i_expiryTime -= diff; + } - bool Passed() const - { - return i_expiryTime <= 0; - } + bool Passed() const + { + return i_expiryTime <= 0; + } - void Reset(time_t interval) - { - i_expiryTime = interval; - } + void Reset(time_t interval) + { + i_expiryTime = interval; + } - time_t GetExpiry() const - { - return i_expiryTime; - } + time_t GetExpiry() const + { + return i_expiryTime; + } - private: +private: - time_t i_expiryTime; + time_t i_expiryTime; }; struct TimeTrackerSmall { - public: +public: - TimeTrackerSmall(uint32 expiry = 0) - : i_expiryTime(expiry) - { - } + TimeTrackerSmall(uint32 expiry = 0) + : i_expiryTime(expiry) + { + } - void Update(int32 diff) - { - i_expiryTime -= diff; - } + void Update(int32 diff) + { + i_expiryTime -= diff; + } - bool Passed() const - { - return i_expiryTime <= 0; - } + bool Passed() const + { + return i_expiryTime <= 0; + } - void Reset(uint32 interval) - { - i_expiryTime = interval; - } + void Reset(uint32 interval) + { + i_expiryTime = interval; + } - int32 GetExpiry() const - { - return i_expiryTime; - } + int32 GetExpiry() const + { + return i_expiryTime; + } - private: +private: - int32 i_expiryTime; + int32 i_expiryTime; }; struct PeriodicTimer { - public: +public: - PeriodicTimer(int32 period, int32 start_time) - : i_period(period), i_expireTime(start_time) - { - } + PeriodicTimer(int32 period, int32 start_time) + : i_period(period), i_expireTime(start_time) + { + } - bool Update(const uint32 diff) - { - if ((i_expireTime -= diff) > 0) - return false; + bool Update(const uint32 diff) + { + if ((i_expireTime -= diff) > 0) + return false; - i_expireTime += i_period > int32(diff) ? i_period : diff; - return true; - } + i_expireTime += i_period > int32(diff) ? i_period : diff; + return true; + } - void SetPeriodic(int32 period, int32 start_time) - { - i_expireTime = start_time; - i_period = period; - } + void SetPeriodic(int32 period, int32 start_time) + { + i_expireTime = start_time; + i_period = period; + } - // Tracker interface - void TUpdate(int32 diff) { i_expireTime -= diff; } - bool TPassed() const { return i_expireTime <= 0; } - void TReset(int32 diff, int32 period) { i_expireTime += period > diff ? period : diff; } + // Tracker interface + void TUpdate(int32 diff) { i_expireTime -= diff; } + bool TPassed() const { return i_expireTime <= 0; } + void TReset(int32 diff, int32 period) { i_expireTime += period > diff ? period : diff; } - private: +private: - int32 i_period; - int32 i_expireTime; + int32 i_period; + int32 i_expireTime; }; #endif diff --git a/src/server/shared/Utilities/Util.cpp b/src/server/shared/Utilities/Util.cpp index ffef61557fc..fc01442adb3 100644 --- a/src/server/shared/Utilities/Util.cpp +++ b/src/server/shared/Utilities/Util.cpp @@ -127,6 +127,18 @@ void stripLineInvisibleChars(std::string &str) } +std::tm localtime_r(const time_t& time) +{ + std::tm tm_snapshot; +#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) + localtime_s(&tm_snapshot, &time); +#else + localtime_r(&time, &tm_snapshot); // POSIX +#endif + return tm_snapshot; +} + + std::string secsToTimeString(uint64 timeInSecs, bool shortText, bool hoursOnly) { uint64 secs = timeInSecs % MINUTE; @@ -215,8 +227,7 @@ uint32 TimeStringToSecs(const std::string& timestring) std::string TimeToTimestampStr(time_t t) { - tm aTm; - ACE_OS::localtime_r(&t, &aTm); + tm aTm = localtime_r(t); // YYYY year // MM month (2 digits 01-12) // DD day (2 digits 01-31) diff --git a/src/server/shared/Utilities/Util.h b/src/server/shared/Utilities/Util.h index b086a28134c..fb40b921bc2 100644 --- a/src/server/shared/Utilities/Util.h +++ b/src/server/shared/Utilities/Util.h @@ -70,6 +70,8 @@ void stripLineInvisibleChars(std::string &src); int32 MoneyStringToMoney(const std::string& moneyString); +std::tm localtime_r(const time_t& time); + std::string secsToTimeString(uint64 timeInSecs, bool shortText = false, bool hoursOnly = false); uint32 TimeStringToSecs(const std::string& timestring); std::string TimeToTimestampStr(time_t t); -- cgit v1.2.3 From 55dee85ed80d43cc0d312d588652f85d9a027297 Mon Sep 17 00:00:00 2001 From: leak Date: Sun, 8 Jun 2014 23:28:01 +0200 Subject: Remove ace/config-all.h and ancient WinXP defines which are actually commented out... --- src/server/shared/Common.h | 5 ----- 1 file changed, 5 deletions(-) (limited to 'src/server/shared/Common.h') diff --git a/src/server/shared/Common.h b/src/server/shared/Common.h index 54c7bfc5be8..f6152fafc8e 100644 --- a/src/server/shared/Common.h +++ b/src/server/shared/Common.h @@ -85,12 +85,7 @@ #include "Threading/Threading.h" #if PLATFORM == PLATFORM_WINDOWS -# include -// XP winver - needed to compile with standard leak check in MemoryLeaks.h -// uncomment later if needed -//#define _WIN32_WINNT 0x0501 # include -//#undef WIN32_WINNT #else # include # include -- cgit v1.2.3 From 33dc72a812ad5fb6e17a26b14d6d7f9aaf5d34b5 Mon Sep 17 00:00:00 2001 From: leak Date: Sat, 21 Jun 2014 19:39:16 +0200 Subject: Replaced Threading and SFMT access related code with std::thread and boost TSS Note: The remote access thread is currently broken due to unknown ACE fail (will be replaced at some point anyways..) --- dep/SFMT/SFMT.h | 87 ++++---- src/server/shared/Common.h | 3 - src/server/shared/Database/MySQLThreading.h | 27 +-- src/server/shared/Threading/Threading.cpp | 235 --------------------- src/server/shared/Threading/Threading.h | 108 ---------- src/server/shared/Utilities/Util.cpp | 37 ++-- src/server/shared/Utilities/Util.h | 3 - src/server/worldserver/CommandLine/CliRunnable.cpp | 2 +- src/server/worldserver/CommandLine/CliRunnable.h | 7 +- src/server/worldserver/Master.cpp | 104 ++++----- src/server/worldserver/RemoteAccess/RARunnable.cpp | 28 ++- src/server/worldserver/RemoteAccess/RARunnable.h | 16 +- src/server/worldserver/TCSoap/TCSoap.cpp | 10 +- src/server/worldserver/TCSoap/TCSoap.h | 22 +- .../worldserver/WorldThread/WorldRunnable.cpp | 7 +- src/server/worldserver/WorldThread/WorldRunnable.h | 7 +- 16 files changed, 138 insertions(+), 565 deletions(-) delete mode 100644 src/server/shared/Threading/Threading.cpp delete mode 100644 src/server/shared/Threading/Threading.h (limited to 'src/server/shared/Common.h') diff --git a/dep/SFMT/SFMT.h b/dep/SFMT/SFMT.h index 4004ae1db6e..3d15d651e5b 100644 --- a/dep/SFMT/SFMT.h +++ b/dep/SFMT/SFMT.h @@ -150,9 +150,13 @@ __m128i const &c, __m128i const &d, __m128i const &mask) { return z2; } +namespace boost { + template class thread_specific_ptr; +} + // Class for SFMT generator class SFMTRand { // Encapsulate random number generator - friend class ACE_TSS; + friend class boost::thread_specific_ptr; public: SFMTRand() @@ -243,6 +247,47 @@ public: y = ((uint32_t*)state)[ix++]; return y; } + + void* operator new(size_t size, std::nothrow_t const&) + { + return _mm_malloc(size, 16); + } + + void operator delete(void* ptr, std::nothrow_t const&) + { + _mm_free(ptr); + } + + void* operator new(size_t size) + { + return _mm_malloc(size, 16); + } + + void operator delete(void* ptr) + { + _mm_free(ptr); + } + + void* operator new[](size_t size, std::nothrow_t const&) + { + return _mm_malloc(size, 16); + } + + void operator delete[](void* ptr, std::nothrow_t const&) + { + _mm_free(ptr); + } + + void* operator new[](size_t size) + { + return _mm_malloc(size, 16); + } + + void operator delete[](void* ptr) + { + _mm_free(ptr); + } + private: void Init2() // Various initializations and period certification { @@ -307,46 +352,6 @@ private: ix = 0; } - void* operator new(size_t size, std::nothrow_t const&) - { - return _mm_malloc(size, 16); - } - - void operator delete(void* ptr, std::nothrow_t const&) - { - _mm_free(ptr); - } - - void* operator new(size_t size) - { - return _mm_malloc(size, 16); - } - - void operator delete(void* ptr) - { - _mm_free(ptr); - } - - void* operator new[](size_t size, std::nothrow_t const&) - { - return _mm_malloc(size, 16); - } - - void operator delete[](void* ptr, std::nothrow_t const&) - { - _mm_free(ptr); - } - - void* operator new[](size_t size) - { - return _mm_malloc(size, 16); - } - - void operator delete[](void* ptr) - { - _mm_free(ptr); - } - __m128i mask; // AND mask __m128i state[SFMT_N]; // State vector for SFMT generator uint32_t ix; // Index into state array diff --git a/src/server/shared/Common.h b/src/server/shared/Common.h index f6152fafc8e..8cab769ec8a 100644 --- a/src/server/shared/Common.h +++ b/src/server/shared/Common.h @@ -82,7 +82,6 @@ #include "Debugging/Errors.h" #include "Threading/LockedQueue.h" -#include "Threading/Threading.h" #if PLATFORM == PLATFORM_WINDOWS # include @@ -114,8 +113,6 @@ inline float finiteAlways(float f) { return finite(f) ? f : 0.0f; } -#define atol(a) strtoul( a, NULL, 10) - #define STRINGIZE(a) #a enum TimeConstants diff --git a/src/server/shared/Database/MySQLThreading.h b/src/server/shared/Database/MySQLThreading.h index 0f6af8ace20..da234138879 100644 --- a/src/server/shared/Database/MySQLThreading.h +++ b/src/server/shared/Database/MySQLThreading.h @@ -23,31 +23,6 @@ class MySQL { public: - /*! Create a thread on the MySQL server to mirrior the calling thread, - initializes thread-specific variables and allows thread-specific - operations without concurrence from other threads. - This should only be called if multiple core threads are running - on the same MySQL connection. Seperate MySQL connections implicitly - create a mirror thread. - */ - static void Thread_Init() - { - mysql_thread_init(); - TC_LOG_WARN("sql.sql", "Core thread with ID [" UI64FMTD "] initializing MySQL thread.", - (uint64)ACE_Based::Thread::currentId()); - } - - /*! Shuts down MySQL thread and frees resources, should only be called - when we terminate. MySQL threads and connections are not configurable - during runtime. - */ - static void Thread_End() - { - mysql_thread_end(); - TC_LOG_WARN("sql.sql", "Core thread with ID [" UI64FMTD "] shutting down MySQL thread.", - (uint64)ACE_Based::Thread::currentId()); - } - static void Library_Init() { mysql_library_init(-1, NULL, NULL); @@ -59,4 +34,4 @@ class MySQL } }; -#endif \ No newline at end of file +#endif diff --git a/src/server/shared/Threading/Threading.cpp b/src/server/shared/Threading/Threading.cpp deleted file mode 100644 index f67a985943a..00000000000 --- a/src/server/shared/Threading/Threading.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore - * Copyright (C) 2005-2008 MaNGOS - * - * 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, see . - */ - -#include "Threading.h" -#include "Errors.h" -#include -#include -#include - -using namespace ACE_Based; - -ThreadPriority::ThreadPriority() -{ - for (int i = Idle; i < MAXPRIORITYNUM; ++i) - m_priority[i] = ACE_THR_PRI_OTHER_DEF; - - m_priority[Idle] = ACE_Sched_Params::priority_min(ACE_SCHED_OTHER); - m_priority[Realtime] = ACE_Sched_Params::priority_max(ACE_SCHED_OTHER); - - std::vector _tmp; - - ACE_Sched_Params::Policy _policy = ACE_SCHED_OTHER; - ACE_Sched_Priority_Iterator pr_iter(_policy); - - while (pr_iter.more()) - { - _tmp.push_back(pr_iter.priority()); - pr_iter.next(); - } - - ASSERT (!_tmp.empty()); - - if (_tmp.size() >= MAXPRIORITYNUM) - { - const size_t max_pos = _tmp.size(); - size_t min_pos = 1; - size_t norm_pos = 0; - for (size_t i = 0; i < max_pos; ++i) - { - if (_tmp[i] == ACE_THR_PRI_OTHER_DEF) - { - norm_pos = i + 1; - break; - } - } - - // since we have only 7(seven) values in enum Priority - // and 3 we know already (Idle, Normal, Realtime) so - // we need to split each list [Idle...Normal] and [Normal...Realtime] - // into pieces - const size_t _divider = 4; - size_t _div = (norm_pos - min_pos) / _divider; - if (_div == 0) - _div = 1; - - min_pos = (norm_pos - 1); - - m_priority[Low] = _tmp[min_pos -= _div]; - m_priority[Lowest] = _tmp[min_pos -= _div ]; - - _div = (max_pos - norm_pos) / _divider; - if (_div == 0) - _div = 1; - - min_pos = norm_pos - 1; - - m_priority[High] = _tmp[min_pos += _div]; - m_priority[Highest] = _tmp[min_pos += _div]; - } -} - -int ThreadPriority::getPriority(Priority p) const -{ - if (p < Idle) - p = Idle; - - if (p > Realtime) - p = Realtime; - - return m_priority[p]; -} - -#define THREADFLAG (THR_NEW_LWP | THR_SCHED_DEFAULT| THR_JOINABLE) - -Thread::Thread(): m_iThreadId(0), m_hThreadHandle(0), m_task(0) -{ - -} - -Thread::Thread(Runnable* instance): m_iThreadId(0), m_hThreadHandle(0), m_task(instance) -{ - // register reference to m_task to prevent it deeltion until destructor - if (m_task) - m_task->incReference(); - - bool _start = start(); - ASSERT (_start); -} - -Thread::~Thread() -{ - //Wait(); - - // deleted runnable object (if no other references) - if (m_task) - m_task->decReference(); -} - -//initialize Thread's class static member -Thread::ThreadStorage Thread::m_ThreadStorage; -ThreadPriority Thread::m_TpEnum; - -bool Thread::start() -{ - if (m_task == 0 || m_iThreadId != 0) - return false; - - // incRef before spawing the thread, otherwise Thread::ThreadTask() might call decRef and delete m_task - m_task->incReference(); - - bool res = (ACE_Thread::spawn(&Thread::ThreadTask, (void*)m_task, THREADFLAG, &m_iThreadId, &m_hThreadHandle) == 0); - - if (!res) - m_task->decReference(); - - return res; -} - -bool Thread::wait() -{ - if (!m_hThreadHandle || !m_task) - return false; - - ACE_THR_FUNC_RETURN _value = ACE_THR_FUNC_RETURN(-1); - int _res = ACE_Thread::join(m_hThreadHandle, &_value); - - m_iThreadId = 0; - m_hThreadHandle = 0; - - return (_res == 0); -} - -void Thread::destroy() -{ - if (!m_iThreadId || !m_task) - return; - - if (ACE_Thread::kill(m_iThreadId, -1) != 0) - return; - - m_iThreadId = 0; - m_hThreadHandle = 0; - - // reference set at ACE_Thread::spawn - m_task->decReference(); -} - -void Thread::suspend() -{ - ACE_Thread::suspend(m_hThreadHandle); -} - -void Thread::resume() -{ - ACE_Thread::resume(m_hThreadHandle); -} - -ACE_THR_FUNC_RETURN Thread::ThreadTask(void * param) -{ - Runnable* _task = (Runnable*)param; - _task->run(); - - // task execution complete, free referecne added at - _task->decReference(); - - return (ACE_THR_FUNC_RETURN)0; -} - -ACE_thread_t Thread::currentId() -{ - return ACE_Thread::self(); -} - -ACE_hthread_t Thread::currentHandle() -{ - ACE_hthread_t _handle; - ACE_Thread::self(_handle); - - return _handle; -} - -Thread * Thread::current() -{ - Thread * _thread = m_ThreadStorage.ts_object(); - if (!_thread) - { - _thread = new Thread(); - _thread->m_iThreadId = Thread::currentId(); - _thread->m_hThreadHandle = Thread::currentHandle(); - - Thread * _oldValue = m_ThreadStorage.ts_object(_thread); - if (_oldValue) - delete _oldValue; - } - - return _thread; -} - -void Thread::setPriority(Priority type) -{ - int _priority = m_TpEnum.getPriority(type); - int _ok = ACE_Thread::setprio(m_hThreadHandle, _priority); - //remove this ASSERT in case you don't want to know is thread priority change was successful or not - ASSERT (_ok == 0); -} - -void Thread::Sleep(unsigned long msecs) -{ - ACE_OS::sleep(ACE_Time_Value(0, 1000 * msecs)); -} diff --git a/src/server/shared/Threading/Threading.h b/src/server/shared/Threading/Threading.h deleted file mode 100644 index 9d416109e9f..00000000000 --- a/src/server/shared/Threading/Threading.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (C) 2008-2014 TrinityCore - * Copyright (C) 2005-2008 MaNGOS - * - * 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, see . - */ - -#ifndef THREADING_H -#define THREADING_H - -#include -#include -#include -#include - -namespace ACE_Based -{ - - class Runnable - { - public: - virtual ~Runnable() { } - virtual void run() = 0; - - void incReference() { ++m_refs; } - void decReference() - { - if (!--m_refs) - delete this; - } - private: - ACE_Atomic_Op m_refs; - }; - - enum Priority - { - Idle, - Lowest, - Low, - Normal, - High, - Highest, - Realtime - }; - -#define MAXPRIORITYNUM (Realtime + 1) - - class ThreadPriority - { - public: - ThreadPriority(); - int getPriority(Priority p) const; - - private: - int m_priority[MAXPRIORITYNUM]; - }; - - class Thread - { - public: - Thread(); - explicit Thread(Runnable* instance); - ~Thread(); - - bool start(); - bool wait(); - void destroy(); - - void suspend(); - void resume(); - - void setPriority(Priority type); - - static void Sleep(unsigned long msecs); - static ACE_thread_t currentId(); - static ACE_hthread_t currentHandle(); - static Thread * current(); - - private: - Thread(const Thread&); - Thread& operator=(const Thread&); - - static ACE_THR_FUNC_RETURN ThreadTask(void * param); - - ACE_thread_t m_iThreadId; - ACE_hthread_t m_hThreadHandle; - Runnable* m_task; - - typedef ACE_TSS ThreadStorage; - //global object - container for Thread class representation of every thread - static ThreadStorage m_ThreadStorage; - //use this object to determine current OS thread priority values mapped to enum Priority{ } - static ThreadPriority m_TpEnum; - }; - -} -#endif diff --git a/src/server/shared/Utilities/Util.cpp b/src/server/shared/Utilities/Util.cpp index fc01442adb3..c766cc3ca91 100644 --- a/src/server/shared/Utilities/Util.cpp +++ b/src/server/shared/Utilities/Util.cpp @@ -21,42 +21,54 @@ #include "utf8.h" #include "SFMT.h" #include "Errors.h" // for ASSERT -#include +#include -typedef ACE_TSS SFMTRandTSS; -static SFMTRandTSS sfmtRand; +static boost::thread_specific_ptr sfmtRand; + +static SFMTRand* GetRng() +{ + SFMTRand* rand = sfmtRand.get(); + + if (!rand) + { + rand = new SFMTRand(); + sfmtRand.reset(rand); + } + + return rand; +} int32 irand(int32 min, int32 max) { ASSERT(max >= min); - return int32(sfmtRand->IRandom(min, max)); + return int32(GetRng()->IRandom(min, max)); } uint32 urand(uint32 min, uint32 max) { ASSERT(max >= min); - return sfmtRand->URandom(min, max); + return GetRng()->URandom(min, max); } float frand(float min, float max) { ASSERT(max >= min); - return float(sfmtRand->Random() * (max - min) + min); + return float(GetRng()->Random() * (max - min) + min); } int32 rand32() { - return int32(sfmtRand->BRandom()); + return int32(GetRng()->BRandom()); } double rand_norm(void) { - return sfmtRand->Random(); + return GetRng()->Random(); } double rand_chance(void) { - return sfmtRand->Random() * 100.0; + return GetRng()->Random() * 100.0; } Tokenizer::Tokenizer(const std::string &src, const char sep, uint32 vectorReserve) @@ -250,13 +262,6 @@ bool IsIPAddress(char const* ipaddress) return inet_addr(ipaddress) != INADDR_NONE; } -std::string GetAddressString(ACE_INET_Addr const& addr) -{ - char buf[ACE_MAX_FULLY_QUALIFIED_NAME_LEN + 16]; - addr.addr_to_string(buf, ACE_MAX_FULLY_QUALIFIED_NAME_LEN + 16); - return buf; -} - bool IsIPAddrInNetwork(ACE_INET_Addr const& net, ACE_INET_Addr const& addr, ACE_INET_Addr const& subnetMask) { uint32 mask = subnetMask.get_ip_address(); diff --git a/src/server/shared/Utilities/Util.h b/src/server/shared/Utilities/Util.h index fb40b921bc2..af28afd66ff 100644 --- a/src/server/shared/Utilities/Util.h +++ b/src/server/shared/Utilities/Util.h @@ -351,9 +351,6 @@ bool IsIPAddress(char const* ipaddress); /// Checks if address belongs to the a network with specified submask bool IsIPAddrInNetwork(ACE_INET_Addr const& net, ACE_INET_Addr const& addr, ACE_INET_Addr const& subnetMask); -/// Transforms ACE_INET_Addr address into string format "dotted_ip:port" -std::string GetAddressString(ACE_INET_Addr const& addr); - uint32 CreatePIDFile(const std::string& filename); std::string ByteArrayToHexStr(uint8 const* bytes, uint32 length, bool reverse = false); diff --git a/src/server/worldserver/CommandLine/CliRunnable.cpp b/src/server/worldserver/CommandLine/CliRunnable.cpp index ac46b218305..295e63c696b 100644 --- a/src/server/worldserver/CommandLine/CliRunnable.cpp +++ b/src/server/worldserver/CommandLine/CliRunnable.cpp @@ -131,7 +131,7 @@ int kb_hit_return() #endif /// %Thread start -void CliRunnable::run() +void CliThread() { ///- Display the list of available CLI functions then beep //TC_LOG_INFO("server.worldserver", ""); diff --git a/src/server/worldserver/CommandLine/CliRunnable.h b/src/server/worldserver/CommandLine/CliRunnable.h index 5510173973e..7ed3a44995f 100644 --- a/src/server/worldserver/CommandLine/CliRunnable.h +++ b/src/server/worldserver/CommandLine/CliRunnable.h @@ -23,12 +23,7 @@ #ifndef __CLIRUNNABLE_H #define __CLIRUNNABLE_H -/// Command Line Interface handling thread -class CliRunnable : public ACE_Based::Runnable -{ - public: - void run() override; -}; +void CliThread(); #endif diff --git a/src/server/worldserver/Master.cpp b/src/server/worldserver/Master.cpp index a5230b908ef..82c547cad40 100644 --- a/src/server/worldserver/Master.cpp +++ b/src/server/worldserver/Master.cpp @@ -20,6 +20,8 @@ \ingroup Trinityd */ +#include + #include #include "Common.h" @@ -78,51 +80,35 @@ class WorldServerSignalHandler : public Trinity::SignalHandler } }; -class FreezeDetectorRunnable : public ACE_Based::Runnable +void FreezeDetectorThread(uint32 delayTime) { -private: - uint32 _loops; - uint32 _lastChange; - uint32 _delaytime; -public: - FreezeDetectorRunnable() - { - _loops = 0; - _lastChange = 0; - _delaytime = 0; - } + if (!delayTime) + return; - void SetDelayTime(uint32 t) { _delaytime = t; } + TC_LOG_INFO("server.worldserver", "Starting up anti-freeze thread (%u seconds max stuck time)...", delayTime / 1000); + uint32 loops = 0; + uint32 lastChange = 0; - void run() override + while (!World::IsStopped()) { - if (!_delaytime) - return; - - TC_LOG_INFO("server.worldserver", "Starting up anti-freeze thread (%u seconds max stuck time)...", _delaytime/1000); - _loops = 0; - _lastChange = 0; - while (!World::IsStopped()) + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + uint32 curtime = getMSTime(); + // normal work + uint32 worldLoopCounter = World::m_worldLoopCounter.value(); + if (loops != worldLoopCounter) { - ACE_Based::Thread::Sleep(1000); - uint32 curtime = getMSTime(); - // normal work - uint32 worldLoopCounter = World::m_worldLoopCounter.value(); - if (_loops != worldLoopCounter) - { - _lastChange = curtime; - _loops = worldLoopCounter; - } - // possible freeze - else if (getMSTimeDiff(_lastChange, curtime) > _delaytime) - { - TC_LOG_ERROR("server.worldserver", "World Thread hangs, kicking out server!"); - ASSERT(false); - } + lastChange = curtime; + loops = worldLoopCounter; + } + // possible freeze + else if (getMSTimeDiff(lastChange, curtime) > delayTime) + { + TC_LOG_ERROR("server.worldserver", "World Thread hangs, kicking out server!"); + ASSERT(false); } - TC_LOG_INFO("server.worldserver", "Anti-freeze thread exiting without problems."); } -}; + TC_LOG_INFO("server.worldserver", "Anti-freeze thread exiting without problems."); +} /// Main function int Master::Run() @@ -182,10 +168,10 @@ int Master::Run() #endif ///- Launch WorldRunnable thread - ACE_Based::Thread worldThread(new WorldRunnable); - worldThread.setPriority(ACE_Based::Highest); - ACE_Based::Thread* cliThread = NULL; + std::thread worldThread(WorldThread); + + std::thread* cliThread = NULL; #ifdef _WIN32 if (sConfigMgr->GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/) @@ -194,10 +180,10 @@ int Master::Run() #endif { ///- Launch CliRunnable thread - cliThread = new ACE_Based::Thread(new CliRunnable); + cliThread = new std::thread(CliThread); } - ACE_Based::Thread rarThread(new RARunnable); + std::thread rarThread(RemoteAccessThread); #if defined(_WIN32) || defined(__linux__) @@ -268,22 +254,19 @@ int Master::Run() #endif //Start soap serving thread - ACE_Based::Thread* soapThread = NULL; + std::thread* soapThread = nullptr; if (sConfigMgr->GetBoolDefault("SOAP.Enabled", false)) { - TCSoapRunnable* runnable = new TCSoapRunnable(); - runnable->SetListenArguments(sConfigMgr->GetStringDefault("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetIntDefault("SOAP.Port", 7878))); - soapThread = new ACE_Based::Thread(runnable); + soapThread = new std::thread(TCSoapThread, sConfigMgr->GetStringDefault("SOAP.IP", "127.0.0.1"), uint16(sConfigMgr->GetIntDefault("SOAP.Port", 7878))); } + std::thread* freezeDetectorThread = nullptr; + ///- Start up freeze catcher thread if (uint32 freezeDelay = sConfigMgr->GetIntDefault("MaxCoreStuckTime", 0)) { - FreezeDetectorRunnable* fdr = new FreezeDetectorRunnable(); - fdr->SetDelayTime(freezeDelay * 1000); - ACE_Based::Thread freezeThread(fdr); - freezeThread.setPriority(ACE_Based::Highest); + freezeDetectorThread = new std::thread(FreezeDetectorThread, freezeDelay); } ///- Launch the world listener socket @@ -304,13 +287,12 @@ int Master::Run() // when the main thread closes the singletons get unloaded // since worldrunnable uses them, it will crash if unloaded after master - worldThread.wait(); - rarThread.wait(); + worldThread.join(); + //rarThread.join(); - if (soapThread) + if (soapThread != nullptr) { - soapThread->wait(); - soapThread->destroy(); + soapThread->join(); delete soapThread; } @@ -324,7 +306,7 @@ int Master::Run() TC_LOG_INFO("server.worldserver", "Halting process..."); - if (cliThread) + if (cliThread != nullptr) { #ifdef _WIN32 @@ -363,17 +345,15 @@ int Master::Run() DWORD numb; WriteConsoleInput(hStdIn, b, 4, &numb); - cliThread->wait(); - - #else - - cliThread->destroy(); + cliThread->join(); #endif delete cliThread; } + delete freezeDetectorThread; + // for some unknown reason, unloading scripts here and not in worldrunnable // fixes a memory leak related to detaching threads from the module //UnloadScriptingModule(); diff --git a/src/server/worldserver/RemoteAccess/RARunnable.cpp b/src/server/worldserver/RemoteAccess/RARunnable.cpp index 44b07163294..4efeb07ef25 100644 --- a/src/server/worldserver/RemoteAccess/RARunnable.cpp +++ b/src/server/worldserver/RemoteAccess/RARunnable.cpp @@ -33,29 +33,22 @@ #include "RASocket.h" -RARunnable::RARunnable() + +void RemoteAccessThread() { - ACE_Reactor_Impl* imp; + ACE_Reactor_Impl* imp = nullptr; #if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) imp = new ACE_Dev_Poll_Reactor(); - imp->max_notify_iterations (128); - imp->restart (1); + imp->max_notify_iterations(128); + imp->restart(1); #else imp = new ACE_TP_Reactor(); - imp->max_notify_iterations (128); + imp->max_notify_iterations(128); #endif - m_Reactor = new ACE_Reactor (imp, 1); -} + ACE_Reactor* reactor = new ACE_Reactor(imp, 1); -RARunnable::~RARunnable() -{ - delete m_Reactor; -} - -void RARunnable::run() -{ if (!sConfigMgr->GetBoolDefault("Ra.Enable", false)) return; @@ -65,7 +58,7 @@ void RARunnable::run() std::string stringIp = sConfigMgr->GetStringDefault("Ra.IP", "0.0.0.0"); ACE_INET_Addr listenAddress(raPort, stringIp.c_str()); - if (acceptor.open(listenAddress, m_Reactor) == -1) + if (acceptor.open(listenAddress, reactor) == -1) { TC_LOG_ERROR("server.worldserver", "Trinity RA can not bind to port %d on %s", raPort, stringIp.c_str()); return; @@ -76,9 +69,12 @@ void RARunnable::run() while (!World::IsStopped()) { ACE_Time_Value interval(0, 100000); - if (m_Reactor->run_reactor_event_loop(interval) == -1) + if (reactor->run_reactor_event_loop(interval) == -1) break; } + delete imp; + delete reactor; + TC_LOG_DEBUG("server.worldserver", "Trinity RA thread exiting"); } diff --git a/src/server/worldserver/RemoteAccess/RARunnable.h b/src/server/worldserver/RemoteAccess/RARunnable.h index 540ac762f30..a65df077f97 100644 --- a/src/server/worldserver/RemoteAccess/RARunnable.h +++ b/src/server/worldserver/RemoteAccess/RARunnable.h @@ -22,21 +22,7 @@ #ifndef _TRINITY_RARUNNABLE_H_ #define _TRINITY_RARUNNABLE_H_ -#include "Common.h" - -#include - -class RARunnable : public ACE_Based::Runnable -{ -public: - RARunnable(); - virtual ~RARunnable(); - void run() override; - -private: - ACE_Reactor* m_Reactor; - -}; +void RemoteAccessThread(); #endif /* _TRINITY_RARUNNABLE_H_ */ diff --git a/src/server/worldserver/TCSoap/TCSoap.cpp b/src/server/worldserver/TCSoap/TCSoap.cpp index 1549019352d..3d242859ff2 100644 --- a/src/server/worldserver/TCSoap/TCSoap.cpp +++ b/src/server/worldserver/TCSoap/TCSoap.cpp @@ -22,7 +22,7 @@ #include "AccountMgr.h" #include "Log.h" -void TCSoapRunnable::run() +void TCSoapThread(const std::string& host, uint16 port) { struct soap soap; soap_init(&soap); @@ -33,13 +33,13 @@ void TCSoapRunnable::run() soap.accept_timeout = 3; soap.recv_timeout = 5; soap.send_timeout = 5; - if (!soap_valid_socket(soap_bind(&soap, _host.c_str(), _port, 100))) + if (!soap_valid_socket(soap_bind(&soap, host.c_str(), port, 100))) { - TC_LOG_ERROR("network.soap", "Couldn't bind to %s:%d", _host.c_str(), _port); + TC_LOG_ERROR("network.soap", "Couldn't bind to %s:%d", host.c_str(), port); exit(-1); } - TC_LOG_INFO("network.soap", "Bound to http://%s:%d", _host.c_str(), _port); + TC_LOG_INFO("network.soap", "Bound to http://%s:%d", host.c_str(), port); while (!World::IsStopped()) { @@ -57,7 +57,7 @@ void TCSoapRunnable::run() soap_done(&soap); } -void TCSoapRunnable::process_message(ACE_Message_Block* mb) +void process_message(ACE_Message_Block* mb) { ACE_TRACE (ACE_TEXT ("SOAPWorkingThread::process_message")); diff --git a/src/server/worldserver/TCSoap/TCSoap.h b/src/server/worldserver/TCSoap/TCSoap.h index 427d37ef0cc..937ceac6425 100644 --- a/src/server/worldserver/TCSoap/TCSoap.h +++ b/src/server/worldserver/TCSoap/TCSoap.h @@ -22,27 +22,9 @@ #include #include -#include -class TCSoapRunnable : public ACE_Based::Runnable -{ - public: - TCSoapRunnable() : _port(0) { } - - void run() override; - - void SetListenArguments(const std::string& host, uint16 port) - { - _host = host; - _port = port; - } - - private: - void process_message(ACE_Message_Block* mb); - - std::string _host; - uint16 _port; -}; +void process_message(ACE_Message_Block* mb); +void TCSoapThread(const std::string& host, uint16 port); class SOAPCommand { diff --git a/src/server/worldserver/WorldThread/WorldRunnable.cpp b/src/server/worldserver/WorldThread/WorldRunnable.cpp index 476007f6ea0..7722492b5a8 100644 --- a/src/server/worldserver/WorldThread/WorldRunnable.cpp +++ b/src/server/worldserver/WorldThread/WorldRunnable.cpp @@ -20,6 +20,8 @@ \ingroup Trinityd */ +#include + #include "Common.h" #include "ObjectAccessor.h" #include "World.h" @@ -40,7 +42,7 @@ extern int m_ServiceStatus; #endif /// Heartbeat for the World -void WorldRunnable::run() +void WorldThread() { uint32 realCurrTime = 0; uint32 realPrevTime = getMSTime(); @@ -67,7 +69,8 @@ void WorldRunnable::run() if (diff <= WORLD_SLEEP_CONST+prevSleepTime) { prevSleepTime = WORLD_SLEEP_CONST+prevSleepTime-diff; - ACE_Based::Thread::Sleep(prevSleepTime); + + std::this_thread::sleep_for(std::chrono::milliseconds(prevSleepTime)); } else prevSleepTime = 0; diff --git a/src/server/worldserver/WorldThread/WorldRunnable.h b/src/server/worldserver/WorldThread/WorldRunnable.h index dfc74dd1e3a..915bd5b580a 100644 --- a/src/server/worldserver/WorldThread/WorldRunnable.h +++ b/src/server/worldserver/WorldThread/WorldRunnable.h @@ -23,12 +23,7 @@ #ifndef __WORLDRUNNABLE_H #define __WORLDRUNNABLE_H -/// Heartbeat thread for the World -class WorldRunnable : public ACE_Based::Runnable -{ - public: - void run() override; -}; +void WorldThread(); #endif -- cgit v1.2.3