diff --git a/contrib/mmap/CMakeLists.txt b/contrib/mmap/CMakeLists.txt index f95eb3d67..abc081811 100644 --- a/contrib/mmap/CMakeLists.txt +++ b/contrib/mmap/CMakeLists.txt @@ -28,6 +28,7 @@ include_directories( ../../src/shared ../../src/game ../../src/game/vmap + ../../src/game/Maps ../../src/game/Commands ../../dep/include/g3dlite ../../src/framework diff --git a/contrib/mmap/src/TerrainBuilder.cpp b/contrib/mmap/src/TerrainBuilder.cpp index a7d9fa1ac..0d2230720 100644 --- a/contrib/mmap/src/TerrainBuilder.cpp +++ b/contrib/mmap/src/TerrainBuilder.cpp @@ -603,7 +603,7 @@ namespace MMAP ModelInstance& instance = models[i]; // model instances exist in tree even though there are instances of that model in this tile - WorldModel* worldModel = instance.getWorldModel(); + std::shared_ptr worldModel = instance.getWorldModel(); if (!worldModel) continue; @@ -730,7 +730,7 @@ namespace MMAP ModelInstance instance = models[i]; // model instances exist in tree even though there are instances of that model in this tile - WorldModel* worldModel = instance.getWorldModel(); + std::shared_ptr worldModel = instance.getWorldModel(); if (!worldModel) continue; diff --git a/dep/loadlib/CMakeLists.txt b/dep/loadlib/CMakeLists.txt index 2422ec48b..168c08c72 100644 --- a/dep/loadlib/CMakeLists.txt +++ b/dep/loadlib/CMakeLists.txt @@ -23,6 +23,7 @@ include_directories( ) # link loadlib with zlib + if(UNIX) find_package(ZLIB REQUIRED) if(ZLIB_FOUND) diff --git a/src/framework/CMakeLists.txt b/src/framework/CMakeLists.txt index 194287e6b..d495bb378 100644 --- a/src/framework/CMakeLists.txt +++ b/src/framework/CMakeLists.txt @@ -17,41 +17,41 @@ # include(${CMAKE_SOURCE_DIR}/dep/tbb/tbbinclude.cmake) -set (framework_SRCS - Dynamic/FactoryHolder.h - Dynamic/ObjectRegistry.h - GameSystem/Grid.h - GameSystem/GridLoader.h - GameSystem/GridReference.h - GameSystem/GridRefManager.h - GameSystem/NGrid.h - GameSystem/TypeContainer.h - GameSystem/TypeContainerFunctions.h - GameSystem/TypeContainerFunctionsPtr.h - GameSystem/TypeContainerVisitor.h - Network/MangosSocket.h - Network/MangosSocketImpl.h - Network/MangosSocketMgr.h - Network/MangosSocketMgrImpl.h - Platform/CompilerDefs.h - Platform/Define.h - Policies/CreationPolicy.h - Policies/ObjectLifeTime.h - Policies/Singleton.h - Policies/SingletonImp.h - Policies/ThreadingModel.h - Utilities/ByteConverter.h - Utilities/Callback.h - Utilities/EventProcessor.h - Utilities/EventMap.h - Utilities/LinkedList.h - Utilities/TypeList.h - Utilities/LinkedReference/Reference.h - Utilities/LinkedReference/RefManager.h - Policies/MemoryManagement.cpp - Policies/ObjectLifeTime.cpp - Utilities/EventProcessor.cpp - Utilities/EventMap.cpp +set(framework_SRCS + Dynamic/FactoryHolder.h + Dynamic/ObjectRegistry.h + GameSystem/Grid.h + GameSystem/GridLoader.h + GameSystem/GridReference.h + GameSystem/GridRefManager.h + GameSystem/NGrid.h + GameSystem/TypeContainer.h + GameSystem/TypeContainerFunctions.h + GameSystem/TypeContainerFunctionsPtr.h + GameSystem/TypeContainerVisitor.h + Network/MangosSocket.h + Network/MangosSocketImpl.h + Network/MangosSocketMgr.h + Network/MangosSocketMgrImpl.h + Platform/CompilerDefs.h + Platform/Define.h + Policies/CreationPolicy.h + Policies/ObjectLifeTime.h + Policies/Singleton.h + Policies/SingletonImp.h + Policies/ThreadingModel.h + Utilities/ByteConverter.h + Utilities/Callback.h + Utilities/EventProcessor.h + Utilities/EventMap.h + Utilities/LinkedList.h + Utilities/TypeList.h + Utilities/LinkedReference/Reference.h + Utilities/LinkedReference/RefManager.h + Policies/MemoryManagement.cpp + Policies/ObjectLifeTime.cpp + Utilities/EventProcessor.cpp + Utilities/EventMap.cpp ) diff --git a/src/framework/Network/MangosSocket.h b/src/framework/Network/MangosSocket.h index 677cfff69..f1409ec30 100644 --- a/src/framework/Network/MangosSocket.h +++ b/src/framework/Network/MangosSocket.h @@ -9,10 +9,9 @@ #include #include #include -#include -#include #include #include +#include #if !defined (ACE_LACKS_PRAGMA_ONCE) #pragma once @@ -103,8 +102,8 @@ class MangosSocket : public WorldHandler friend class ACE_NonBlocking_Connect_Handler; /// Mutex type used for various synchronizations. - typedef ACE_Thread_Mutex LockType; - typedef ACE_Guard GuardType; + using LockType = std::mutex; + typedef std::unique_lock GuardType; /// Queue for storing packets for which there is no space. typedef ACE_Unbounded_Queue PacketQueueT; diff --git a/src/framework/Network/MangosSocketImpl.h b/src/framework/Network/MangosSocketImpl.h index 0abb2ce3b..373fa4521 100644 --- a/src/framework/Network/MangosSocketImpl.h +++ b/src/framework/Network/MangosSocketImpl.h @@ -7,7 +7,6 @@ #include #include #include -#include #include "MangosSocket.h" #include "Common.h" @@ -63,7 +62,7 @@ template void MangosSocket::CloseSocket(void) { { - ACE_GUARD(LockType, Guard, m_OutBufferLock); + GuardType lock(m_OutBufferLock); if (closing_) return; @@ -73,7 +72,7 @@ void MangosSocket::CloseSocket(void) } { - ACE_GUARD(LockType, Guard, m_SessionLock); + GuardType lock(m_SessionLock); m_Session = nullptr; } @@ -82,7 +81,7 @@ void MangosSocket::CloseSocket(void) template int MangosSocket::SendPacket(const WorldPacket& pct) { - ACE_GUARD_RETURN(LockType, Guard, m_OutBufferLock, -1); + GuardType lock(m_OutBufferLock); if (closing_) return -1; @@ -205,7 +204,7 @@ int MangosSocket::handle_input(ACE_HANDLE) template int MangosSocket::handle_output(ACE_HANDLE) { - ACE_GUARD_RETURN(LockType, Guard, m_OutBufferLock, -1); + GuardType lock(m_OutBufferLock); if (closing_) return -1; @@ -213,7 +212,7 @@ int MangosSocket::handle_output(ACE_HANDLE) const size_t send_len = m_OutBuffer->length(); if (send_len == 0) - return cancel_wakeup_output(Guard); + return cancel_wakeup_output(lock); #ifdef MSG_NOSIGNAL ssize_t n = peer().send(m_OutBuffer->rd_ptr(), send_len, MSG_NOSIGNAL); @@ -226,7 +225,7 @@ int MangosSocket::handle_output(ACE_HANDLE) else if (n == -1) { if (errno == EWOULDBLOCK || errno == EAGAIN) - return schedule_wakeup_output(Guard); + return schedule_wakeup_output(lock); return -1; } @@ -237,16 +236,16 @@ int MangosSocket::handle_output(ACE_HANDLE) // move the data to the base of the buffer m_OutBuffer->crunch(); - return schedule_wakeup_output(Guard); + return schedule_wakeup_output(lock); } else //now n == send_len { m_OutBuffer->reset(); if (!iFlushPacketQueue()) - return cancel_wakeup_output(Guard); + return cancel_wakeup_output(lock); else - return schedule_wakeup_output(Guard); + return schedule_wakeup_output(lock); } ACE_NOTREACHED(return 0); @@ -257,7 +256,7 @@ int MangosSocket::handle_close(ACE_HANDLE h, ACE { // Critical section { - ACE_GUARD_RETURN(LockType, Guard, m_OutBufferLock, -1); + GuardType lock(m_OutBufferLock); closing_ = true; @@ -267,7 +266,7 @@ int MangosSocket::handle_close(ACE_HANDLE h, ACE // Critical section { - ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1); + GuardType lock(m_SessionLock); m_Session = nullptr; } @@ -448,7 +447,7 @@ int MangosSocket::cancel_wakeup_output(GuardType m_OutActive = false; - g.release(); + g.unlock(); if (reactor()->cancel_wakeup (this, ACE_Event_Handler::WRITE_MASK) == -1) @@ -469,7 +468,7 @@ int MangosSocket::schedule_wakeup_output(GuardTy m_OutActive = true; - g.release(); + g.unlock(); if (reactor()->schedule_wakeup (this, ACE_Event_Handler::WRITE_MASK) == -1) diff --git a/src/framework/Network/MangosSocketMgr.h b/src/framework/Network/MangosSocketMgr.h index 76bb0a90e..a533226d4 100644 --- a/src/framework/Network/MangosSocketMgr.h +++ b/src/framework/Network/MangosSocketMgr.h @@ -2,8 +2,6 @@ #define MANGOSSOCKETMGR_H #include -#include -#include #include diff --git a/src/framework/Network/MangosSocketMgrImpl.h b/src/framework/Network/MangosSocketMgrImpl.h index be05315a1..5144bec17 100644 --- a/src/framework/Network/MangosSocketMgrImpl.h +++ b/src/framework/Network/MangosSocketMgrImpl.h @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include @@ -17,6 +16,7 @@ #include #include +#include #include "Log.h" #include "Common.h" @@ -121,12 +121,12 @@ public: long Connections() { - return static_cast(m_Connections.value()); + return m_Connections; } int AddSocket(SocketType* sock) { - ACE_GUARD_RETURN(ACE_Thread_Mutex, Guard, m_NewSockets_Lock, -1); + std::unique_lock lock(m_NewSockets_Lock); ++m_Connections; sock->AddReference(); @@ -144,7 +144,7 @@ public: protected: void AddNewSockets() { - ACE_GUARD(ACE_Thread_Mutex, Guard, m_NewSockets_Lock); + std::unique_lock lock(m_NewSockets_Lock); if (m_NewSockets.empty()) return; @@ -210,7 +210,7 @@ protected: } private: - typedef ACE_Atomic_Op AtomicInt; + using AtomicInt = std::atomic; typedef std::set SocketSet; ACE_Reactor* m_Reactor; @@ -221,7 +221,7 @@ private: SocketSet m_Sockets; SocketSet m_NewSockets; - ACE_Thread_Mutex m_NewSockets_Lock; + std::mutex m_NewSockets_Lock; }; template diff --git a/src/framework/Policies/ThreadingModel.h b/src/framework/Policies/ThreadingModel.h index da6f43dbf..f247c8602 100644 --- a/src/framework/Policies/ThreadingModel.h +++ b/src/framework/Policies/ThreadingModel.h @@ -28,6 +28,7 @@ */ #include "Platform/Define.h" +#include namespace MaNGOS { @@ -39,115 +40,63 @@ namespace MaNGOS GeneralLock(MUTEX &m) : i_mutex(m) { - i_mutex.acquire(); } ~GeneralLock() { - i_mutex.release(); } + GeneralLock(const GeneralLock &) = delete; + GeneralLock& operator=(const GeneralLock &) = delete; private: - GeneralLock(const GeneralLock &); - GeneralLock& operator=(const GeneralLock &); MUTEX &i_mutex; + std::unique_lock m_lock{i_mutex}; + }; template class SingleThreaded { - public: + public: - struct Lock // empty object - { - Lock() - { - } - Lock(const T&) - { - } + struct Lock // empty object + { + Lock() = default; - Lock(const SingleThreaded&) // for single threaded we ignore this - { - } - }; - }; + Lock(const T&) { } - template - class ObjectLevelLockable - { - public: - - ObjectLevelLockable() - : i_mtx() - { - } - - friend class Lock; - - class Lock - { - public: - - Lock(ObjectLevelLockable &host) - : i_lock(host.i_mtx) - { - } - - private: - - GeneralLock i_lock; - }; - - private: - - // prevent the compiler creating a copy construct - ObjectLevelLockable(const ObjectLevelLockable&); - ObjectLevelLockable& operator=(const ObjectLevelLockable&); - - MUTEX i_mtx; + Lock(const SingleThreaded&) { } // for single threaded we ignore this + }; }; template class ClassLevelLockable { + public: + + ClassLevelLockable() + { + } + + friend class Lock; + + class Lock + { public: - ClassLevelLockable() - { - } + Lock(const T& /*host*/) { } - friend class Lock; - - class Lock - { - public: - - Lock(const T& /*host*/) - { - ClassLevelLockable::si_mtx.acquire(); - } - - Lock(const ClassLevelLockable &) - { - ClassLevelLockable::si_mtx.acquire(); - } - - Lock() - { - ClassLevelLockable::si_mtx.acquire(); - } - - ~Lock() - { - ClassLevelLockable::si_mtx.release(); - } - }; + Lock(const ClassLevelLockable &) { } + Lock() = default; private: + std::unique_lock m_lock{si_mtx}; + }; - static MUTEX si_mtx; + private: + + static MUTEX si_mtx; }; } diff --git a/src/game/Battlegrounds/BattleGroundMgr.h b/src/game/Battlegrounds/BattleGroundMgr.h index 57e595ae7..2d50dd618 100644 --- a/src/game/Battlegrounds/BattleGroundMgr.h +++ b/src/game/Battlegrounds/BattleGroundMgr.h @@ -27,7 +27,6 @@ #include "Common.h" #include "Policies/Singleton.h" #include "BattleGround.h" -#include "ace/Recursive_Thread_Mutex.h" typedef std::map BattleGroundSet; @@ -101,7 +100,7 @@ class BattleGroundQueue bool PlayerLoggedIn(Player* player); //mutex that should not allow changing private data, nor allowing to update Queue during private data change. - ACE_Recursive_Thread_Mutex m_Lock; + std::recursive_mutex m_Lock; typedef std::map QueuedPlayersMap; @@ -296,7 +295,7 @@ class BattleGroundMgr void PlayerLoggedIn(Player* player); void PlayerLoggedOut(Player* player); private: - ACE_Thread_Mutex SchedulerLock; + std::mutex SchedulerLock; BattleMastersMap mBattleMastersMap; CreatureBattleEventIndexesMap m_CreatureBattleEventIndexMap; GameObjectBattleEventIndexesMap m_GameObjectBattleEventIndexMap; diff --git a/src/game/Camera.cpp b/src/game/Camera.cpp index b070ff889..86e2719ef 100644 --- a/src/game/Camera.cpp +++ b/src/game/Camera.cpp @@ -154,9 +154,9 @@ void Camera::UpdateVisibilityForOwner() if (!m_source->FindMap()) return; - GetOwner()->m_visibleGUIDs_lock.acquire_read(); + std::shared_lock lock(GetOwner()->m_visibleGUIDs_lock); MaNGOS::VisibleNotifier notifier(*this); // Will copy m_clientGUIDs - GetOwner()->m_visibleGUIDs_lock.release(); + lock.unlock(); Cell::VisitAllObjects(m_source, notifier, m_source->GetMap()->GetVisibilityDistance()); notifier.Notify(); } diff --git a/src/game/Chat/AsyncCommandHandlers.cpp b/src/game/Chat/AsyncCommandHandlers.cpp index f493b7895..480a108fe 100644 --- a/src/game/Chat/AsyncCommandHandlers.cpp +++ b/src/game/Chat/AsyncCommandHandlers.cpp @@ -226,11 +226,10 @@ void PInfoHandler::HandleResponse(WorldSession* session, PInfoData *data) // the world update void PlayerSearchHandler::HandlePlayerAccountSearchResult(QueryResult*, SqlQueryHolder* queryHolder, int) { - PlayerAccountSearchDisplayTask* task = new PlayerAccountSearchDisplayTask((PlayerSearchQueryHolder*)queryHolder); - sWorld.AddAsyncTask(task); + sWorld.AddAsyncTask(PlayerAccountSearchDisplayTask((PlayerSearchQueryHolder*)queryHolder)); } -void PlayerAccountSearchDisplayTask::run() +void PlayerAccountSearchDisplayTask::operator ()() { // NOTE: Do not currently support console access for these commands WorldSession* session = sWorld.FindSession(holder->GetAccountId()); @@ -296,7 +295,7 @@ void PlayerAccountSearchDisplayTask::run() delete holder; } -void PlayerCharacterLookupDisplayTask::run() +void PlayerCharacterLookupDisplayTask::operator()() { WorldSession* session = sWorld.FindSession(accountId); if (!session) @@ -321,8 +320,7 @@ void PlayerCharacterLookupDisplayTask::run() // Handle the result and create a display task to run in the world update void PlayerSearchHandler::HandlePlayerCharacterLookupResult(QueryResult* result, uint32 accountId, uint32 limit) { - PlayerCharacterLookupDisplayTask* task = new PlayerCharacterLookupDisplayTask(result, accountId, limit); - sWorld.AddAsyncTask(task); + sWorld.AddAsyncTask({PlayerCharacterLookupDisplayTask(result, accountId, limit)}); } void PlayerSearchHandler::ShowPlayerListHelper(QueryResult* result, ChatHandler& chatHandler, uint32& count, uint32 limit, bool title) @@ -393,7 +391,7 @@ bool PlayerSearchQueryHolder::GetAccountInfo(uint32 queryIndex, std::pair guard(m_guildMutex); + std::lock_guard guard(m_guildMutex); m_GuildMap[guild->GetId()] = guild; } void GuildMgr::RemoveGuild(uint32 guildId) { - ACE_Guard guard(m_guildMutex); + std::lock_guard guard(m_guildMutex); m_GuildMap.erase(guildId); } Guild* GuildMgr::GetGuildById(uint32 guildId) const { - ACE_Guard guard(m_guildMutex); + std::lock_guard guard(m_guildMutex); GuildMap::const_iterator itr = m_GuildMap.find(guildId); if (itr != m_GuildMap.end()) return itr->second; @@ -73,7 +73,7 @@ Guild* GuildMgr::GetGuildById(uint32 guildId) const Guild* GuildMgr::GetGuildByName(std::string const& name) const { - ACE_Guard guard(m_guildMutex); + std::lock_guard guard(m_guildMutex); for (const auto& itr : m_GuildMap) if (itr.second->GetName() == name) return itr.second; @@ -83,7 +83,7 @@ Guild* GuildMgr::GetGuildByName(std::string const& name) const Guild* GuildMgr::GetGuildByLeader(ObjectGuid const& guid) const { - ACE_Guard guard(m_guildMutex); + std::lock_guard guard(m_guildMutex); for (const auto& itr : m_GuildMap) if (itr.second->GetLeaderGuid() == guid) return itr.second; @@ -93,7 +93,7 @@ Guild* GuildMgr::GetGuildByLeader(ObjectGuid const& guid) const std::string GuildMgr::GetGuildNameById(uint32 guildId) const { - ACE_Guard guard(m_guildMutex); + std::lock_guard guard(m_guildMutex); GuildMap::const_iterator itr = m_GuildMap.find(guildId); if (itr != m_GuildMap.end()) return itr->second->GetName(); @@ -266,13 +266,13 @@ void GuildMgr::CreatePetition(uint32 id, Player* player, ObjectGuid const& chart petition->SetTeam(player->GetTeam()); petition->SaveToDB(); - ACE_Guard guard(m_petitionsMutex); + std::lock_guard guard(m_petitionsMutex); m_petitionMap[petition->GetId()] = petition; } void GuildMgr::DeletePetition(Petition* petition) { - ACE_Guard guard(m_petitionsMutex); + std::lock_guard guard(m_petitionsMutex); m_petitionMap.erase(petition->GetId()); petition->Delete(); @@ -281,7 +281,7 @@ void GuildMgr::DeletePetition(Petition* petition) Petition* GuildMgr::GetPetitionById(uint32 id) { - ACE_Guard guard(m_petitionsMutex); + std::lock_guard guard(m_petitionsMutex); PetitionMap::iterator iter = m_petitionMap.find(id); if (iter != m_petitionMap.end()) return iter->second; @@ -291,7 +291,7 @@ Petition* GuildMgr::GetPetitionById(uint32 id) Petition* GuildMgr::GetPetitionByCharterGuid(ObjectGuid const& charterGuid) { - ACE_Guard guard(m_petitionsMutex); + std::lock_guard guard(m_petitionsMutex); for (const auto& iter : m_petitionMap) { Petition* petition = iter.second; @@ -304,7 +304,7 @@ Petition* GuildMgr::GetPetitionByCharterGuid(ObjectGuid const& charterGuid) Petition* GuildMgr::GetPetitionByOwnerGuid(ObjectGuid const& ownerGuid) { - ACE_Guard guard(m_petitionsMutex); + std::lock_guard guard(m_petitionsMutex); for (const auto& iter : m_petitionMap) { Petition* petition = iter.second; diff --git a/src/game/Guild/GuildMgr.h b/src/game/Guild/GuildMgr.h index bade65bc5..ab436afd3 100644 --- a/src/game/Guild/GuildMgr.h +++ b/src/game/Guild/GuildMgr.h @@ -47,17 +47,17 @@ class GuildMgr void GuildMemberAdded(uint32 guildId, uint32 memberGuid) { - ACE_Guard guard(m_guid2GuildMutex); + std::lock_guard guard(m_guid2GuildMutex); m_guid2guild[memberGuid] = guildId; } void GuildMemberRemoved(uint32 memberGuid) { - ACE_Guard guard(m_guid2GuildMutex); + std::lock_guard guard(m_guid2GuildMutex); m_guid2guild.erase(memberGuid); } Guild* GetPlayerGuild(uint32 lowguid) { - ACE_Guard guard(m_guid2GuildMutex); + std::lock_guard guard(m_guid2GuildMutex); std::map::iterator it = m_guid2guild.find(lowguid); if (it != m_guid2guild.end()) return GetGuildById(it->second); @@ -74,12 +74,12 @@ class GuildMgr void LoadPetitions(); private: void CleanUpPetitions(); - mutable ACE_Thread_Mutex m_guildMutex; + mutable std::mutex m_guildMutex; GuildMap m_GuildMap; - ACE_Thread_Mutex m_guid2GuildMutex; + std::mutex m_guid2GuildMutex; std::map m_guid2guild; - ACE_Thread_Mutex m_petitionsMutex; + std::mutex m_petitionsMutex; PetitionMap m_petitionMap; }; diff --git a/src/game/Handlers/AuctionHouseHandler.cpp b/src/game/Handlers/AuctionHouseHandler.cpp index f5c8633f2..b6ffb3e34 100644 --- a/src/game/Handlers/AuctionHouseHandler.cpp +++ b/src/game/Handlers/AuctionHouseHandler.cpp @@ -638,13 +638,13 @@ void WorldSession::HandleAuctionRemoveItem(WorldPacket& recv_data) } -class AuctionHouseClientQueryTask : public AsyncTask, public AuctionHouseClientQuery +class AuctionHouseClientQueryTask : public AuctionHouseClientQuery { public: AuctionHouseClientQueryTask(AuctionClientQueryType type) : _queryType(type) { } - void run() + void operator ()() { if (WorldSession* sess = sWorld.FindSession(accountId)) { @@ -739,20 +739,20 @@ void WorldSession::HandleAuctionListBidderItems(WorldPacket& recv_data) if (GetPlayer()->HasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); - AuctionHouseClientQueryTask* task = new AuctionHouseClientQueryTask(AUCTION_QUERY_LIST_BIDDER); - task->auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry); + AuctionHouseClientQueryTask task(AUCTION_QUERY_LIST_BIDDER); + task.auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry); uint32 outbiddedAuctionId; for (int i = outbiddedCount; i > 0; --i) { recv_data >> outbiddedAuctionId; - task->outbiddedAuctionIds.push_back(outbiddedAuctionId); + task.outbiddedAuctionIds.push_back(outbiddedAuctionId); } - task->accountId = GetAccountId(); - task->listfrom = listfrom; - task->outbiddedCount = outbiddedCount; + task.accountId = GetAccountId(); + task.listfrom = listfrom; + task.outbiddedCount = outbiddedCount; SetReceivedAHListRequest(true); - sWorld.AddAsyncTask(task); + sWorld.AddAsyncTask(std::move(task)); } // this void sends player info about his auctions @@ -776,12 +776,12 @@ void WorldSession::HandleAuctionListOwnerItems(WorldPacket& recv_data) if (GetPlayer()->HasUnitState(UNIT_STAT_DIED)) GetPlayer()->RemoveSpellsCausingAura(SPELL_AURA_FEIGN_DEATH); - AuctionHouseClientQueryTask* task = new AuctionHouseClientQueryTask(AUCTION_QUERY_LIST_OWNER); - task->auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry);; - task->accountId = GetAccountId(); - task->listfrom = listfrom; + AuctionHouseClientQueryTask task(AUCTION_QUERY_LIST_OWNER); + task.auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry);; + task.accountId = GetAccountId(); + task.listfrom = listfrom; SetReceivedAHListRequest(true); - sWorld.AddAsyncTask(task); + sWorld.AddAsyncTask({std::move(task)}); } void WorldSession::HandleAuctionListItems(WorldPacket& recv_data) @@ -792,26 +792,23 @@ void WorldSession::HandleAuctionListItems(WorldPacket& recv_data) ObjectGuid auctioneerGuid; std::string searchedname; - AuctionHouseClientQueryTask* task = new AuctionHouseClientQueryTask(AUCTION_QUERY_LIST); - task->accountId = GetAccountId(); + AuctionHouseClientQueryTask task(AUCTION_QUERY_LIST); + task.accountId = GetAccountId(); recv_data >> auctioneerGuid; - recv_data >> task->listfrom; // start, used for page control listing by 50 elements + recv_data >> task.listfrom; // start, used for page control listing by 50 elements recv_data >> searchedname; - recv_data >> task->levelmin >> task->levelmax; - recv_data >> task->auctionSlotID >> task->auctionMainCategory >> task->auctionSubCategory >> task->quality; - recv_data >> task->usable; + recv_data >> task.levelmin >> task.levelmax; + recv_data >> task.auctionSlotID >> task.auctionMainCategory >> task.auctionSubCategory >> task.quality; + recv_data >> task.usable; AuctionHouseEntry const* auctionHouseEntry = GetCheckedAuctionHouseForAuctioneer(auctioneerGuid); if (!auctionHouseEntry) - { - delete task; return; - } // always return pointer - task->auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry); + task.auctionHouse = sAuctionMgr.GetAuctionsMap(auctionHouseEntry); // remove fake death if (GetPlayer()->HasUnitState(UNIT_STAT_DIED)) @@ -821,13 +818,10 @@ void WorldSession::HandleAuctionListItems(WorldPacket& recv_data) // auctioneerGuid.GetString().c_str(), listfrom, searchedname.c_str(), levelmin, levelmax, auctionSlotID, auctionMainCategory, auctionSubCategory, quality, usable); // converting string that we try to find to lower case - if (!Utf8toWStr(searchedname, task->wsearchedname)) - { - delete task; + if (!Utf8toWStr(searchedname, task.wsearchedname)) return; - } - wstrToLower(task->wsearchedname); + wstrToLower(task.wsearchedname); SetReceivedAHListRequest(true); - sWorld.AddAsyncTask(task); + sWorld.AddAsyncTask(std::move(task)); } diff --git a/src/game/Handlers/MiscHandler.cpp b/src/game/Handlers/MiscHandler.cpp index f53200b66..5a0d19174 100644 --- a/src/game/Handlers/MiscHandler.cpp +++ b/src/game/Handlers/MiscHandler.cpp @@ -77,7 +77,7 @@ void WorldSession::HandleRepopRequestOpcode(WorldPacket& /*recv_data*/) player->RepopAtGraveyard(); } -class WhoListClientQueryTask: public AsyncTask +class WhoListClientQueryTask { public: uint32 accountId; @@ -85,7 +85,7 @@ public: uint32 zoneids[10]; // 10 is client limit std::wstring str[4]; // 4 is client limit std::wstring wplayer_name, wguild_name; - void run() + void operator()() { WorldSession* sess = sWorld.FindSession(accountId); if (!sess) @@ -243,71 +243,71 @@ void WorldSession::HandleWhoOpcode(WorldPacket& recv_data) return; //recv_data.hexlike(); - WhoListClientQueryTask* task = new WhoListClientQueryTask(); - task->accountId = GetAccountId(); + WhoListClientQueryTask task; + task.accountId = GetAccountId(); std::string player_name, guild_name; - recv_data >> task->level_min; // maximal player level, default 0 - recv_data >> task->level_max; // minimal player level, default 100 (MAX_LEVEL) + recv_data >> task.level_min; // maximal player level, default 0 + recv_data >> task.level_max; // minimal player level, default 100 (MAX_LEVEL) recv_data >> player_name; // player name, case sensitive... recv_data >> guild_name; // guild name, case sensitive... - recv_data >> task->racemask; // race mask - recv_data >> task->classmask; // class mask - recv_data >> task->zones_count; // zones count, client limit=10 (2.0.10) + recv_data >> task.racemask; // race mask + recv_data >> task.classmask; // class mask + recv_data >> task.zones_count; // zones count, client limit=10 (2.0.10) - if (task->zones_count > 10) + if (task.zones_count > 10) { - delete task; + // delete task; return; // can't be received from real client or broken packet } - for (uint32 i = 0; i < task->zones_count; ++i) + for (uint32 i = 0; i < task.zones_count; ++i) { uint32 temp; recv_data >> temp; // zone id, 0 if zone is unknown... - task->zoneids[i] = temp; - DEBUG_LOG("Zone %u: %u", i, task->zoneids[i]); + task.zoneids[i] = temp; + DEBUG_LOG("Zone %u: %u", i, task.zoneids[i]); } - recv_data >> task->str_count; // user entered strings count, client limit=4 (checked on 2.0.10) + recv_data >> task.str_count; // user entered strings count, client limit=4 (checked on 2.0.10) - if (task->str_count > 4) + if (task.str_count > 4) { - delete task; + // delete task; return; // can't be received from real client or broken packet } - DEBUG_LOG("Minlvl %u, maxlvl %u, name %s, guild %s, racemask %u, classmask %u, zones %u, strings %u", task->level_min, task->level_max, player_name.c_str(), guild_name.c_str(), task->racemask, task->classmask, task->zones_count, task->str_count); + DEBUG_LOG("Minlvl %u, maxlvl %u, name %s, guild %s, racemask %u, classmask %u, zones %u, strings %u", task.level_min, task.level_max, player_name.c_str(), guild_name.c_str(), task.racemask, task.classmask, task.zones_count, task.str_count); - for (uint32 i = 0; i < task->str_count; ++i) + for (uint32 i = 0; i < task.str_count; ++i) { std::string temp; recv_data >> temp; // user entered string, it used as universal search pattern(guild+player name)? - if (!Utf8toWStr(temp, task->str[i])) + if (!Utf8toWStr(temp, task.str[i])) continue; - wstrToLower(task->str[i]); + wstrToLower(task.str[i]); DEBUG_LOG("String %u: %s", i, temp.c_str()); } - if (!(Utf8toWStr(player_name, task->wplayer_name) && Utf8toWStr(guild_name, task->wguild_name))) + if (!(Utf8toWStr(player_name, task.wplayer_name) && Utf8toWStr(guild_name, task.wguild_name))) { - delete task; + // delete task; return; } - wstrToLower(task->wplayer_name); - wstrToLower(task->wguild_name); + wstrToLower(task.wplayer_name); + wstrToLower(task.wguild_name); // client send in case not set max level value 100 but mangos support 255 max level, // update it to show GMs with characters after 100 level - if (task->level_max >= MAX_LEVEL) - task->level_max = PLAYER_STRONG_MAX_LEVEL; + if (task.level_max >= MAX_LEVEL) + task.level_max = PLAYER_STRONG_MAX_LEVEL; SetReceivedWhoRequest(true); - sWorld.AddAsyncTask(task); + sWorld.AddAsyncTask(std::move(task)); } void WorldSession::HandleLFGOpcode(WorldPacket& recv_data) diff --git a/src/game/InstanceStatistics.cpp b/src/game/InstanceStatistics.cpp index 8f36615f8..fcfc4994b 100644 --- a/src/game/InstanceStatistics.cpp +++ b/src/game/InstanceStatistics.cpp @@ -143,7 +143,7 @@ void InstanceStatisticsMgr::LoadFromDB() void InstanceStatisticsMgr::IncrementWipeCounter(uint32 mapId, uint32 creatureEntry) { uint32 count; - m_wipesMutex.acquire(); + std::unique_lock lock(m_wipesMutex); auto it = m_instanceWipes.find(std::make_pair(mapId, creatureEntry)); if (it == m_instanceWipes.end()) { @@ -155,7 +155,7 @@ void InstanceStatisticsMgr::IncrementWipeCounter(uint32 mapId, uint32 creatureEn it->second.count++; count = it->second.count; } - m_wipesMutex.release(); + lock.unlock(); Save(mapId, creatureEntry, count); } @@ -173,7 +173,7 @@ void InstanceStatisticsMgr::IncrementKillCounter(Creature* pKiller, Player* pVic spellId = spellProto->Id; uint32 count = 0; - m_creatureKillsMutex.acquire(); + std::unique_lock lock(m_creatureKillsMutex); auto it = m_instanceCreatureKills.find(std::make_pair(mapId, creatureEntry)); if (it == m_instanceCreatureKills.end()) { @@ -196,14 +196,14 @@ void InstanceStatisticsMgr::IncrementKillCounter(Creature* pKiller, Player* pVic count = ++it2->second; } } - m_creatureKillsMutex.release(); + lock.unlock(); Save(mapId,creatureEntry,spellId,count); } void InstanceStatisticsMgr::IncrementCustomCounter(eInstanceCustomCounter index, bool save) { - m_customCountersMutex.acquire(); + std::unique_lock lock(m_customCountersMutex); uint32 count; auto it = m_instanceCustomCounters.find(index); if (it == m_instanceCustomCounters.end()) @@ -216,7 +216,7 @@ void InstanceStatisticsMgr::IncrementCustomCounter(eInstanceCustomCounter index, it->second++; count = it->second; } - m_customCountersMutex.release(); + lock.unlock(); if (save) { diff --git a/src/game/InstanceStatistics.h b/src/game/InstanceStatistics.h index fe0faad72..9b6292d41 100644 --- a/src/game/InstanceStatistics.h +++ b/src/game/InstanceStatistics.h @@ -20,7 +20,6 @@ #define INSTANCE_STATISTICS_H #include "Common.h" -#include "Threading.h" enum eInstanceCustomCounter : int { @@ -65,13 +64,13 @@ private: std::map,InstanceCreatureKlls> m_instanceCreatureKills; std::map m_instanceCustomCounters; - ACE_Thread_Mutex m_wipesMutex; - ACE_Thread_Mutex m_creatureKillsMutex; - ACE_Thread_Mutex m_customCountersMutex; + std::mutex m_wipesMutex; + std::mutex m_creatureKillsMutex; + std::mutex m_customCountersMutex; }; #define sInstanceStatistics MaNGOS::Singleton::Instance() -#endif \ No newline at end of file +#endif diff --git a/src/game/Mail/MassMailMgr.h b/src/game/Mail/MassMailMgr.h index f0d8b39a8..672e285a7 100644 --- a/src/game/Mail/MassMailMgr.h +++ b/src/game/Mail/MassMailMgr.h @@ -89,7 +89,7 @@ class MassMailMgr */ ReceiversList& AddMassMailTask(MailDraft* mailProto, MailSender const& sender) { - m_massMails.push_back(MassMail(mailProto, sender)); + m_massMails.emplace_back(mailProto, sender); return m_massMails.rbegin()->m_receivers; } diff --git a/src/game/Maps/GridMap.cpp b/src/game/Maps/GridMap.cpp index cf463cc90..4d515faac 100644 --- a/src/game/Maps/GridMap.cpp +++ b/src/game/Maps/GridMap.cpp @@ -39,7 +39,7 @@ char const* MAP_LIQUID_MAGIC = "MLIQ"; GridMap::GridMap() { - m_flags = 0; + // m_flags = 0; // Area data m_gridArea = 0; @@ -1205,9 +1205,9 @@ float TerrainInfo::GetWaterLevel(float x, float y, float z, float* pGround /*= n } ////////////////////////////////////////////////////////////////////////// -typedef MaNGOS::ClassLevelLockable TerrainManagerLock; +typedef MaNGOS::ClassLevelLockable TerrainManagerLock; INSTANTIATE_SINGLETON_2(TerrainManager, TerrainManagerLock); -INSTANTIATE_CLASS_MUTEX(TerrainManager, ACE_Thread_Mutex); +INSTANTIATE_CLASS_MUTEX(TerrainManager, std::mutex); TerrainManager::TerrainManager() { diff --git a/src/game/Maps/GridMap.h b/src/game/Maps/GridMap.h index ac0556ea4..90088d5b9 100644 --- a/src/game/Maps/GridMap.h +++ b/src/game/Maps/GridMap.h @@ -29,6 +29,15 @@ #include #include #include +#include + + +#define MAX_HEIGHT 100000.0f // can be use for find ground height at surface +#define INVALID_HEIGHT -100000.0f // for check, must be equal to VMAP_INVALID_HEIGHT, real value for unknown height is VMAP_INVALID_HEIGHT_VALUE +#define INVALID_HEIGHT_VALUE -200000.0f // for return, must be equal to VMAP_INVALID_HEIGHT_VALUE, check value for unknown height is VMAP_INVALID_HEIGHT +#define MAX_FALL_DISTANCE 250000.0f // "unlimited fall" to find VMap ground if it is available, just larger than MAX_HEIGHT - INVALID_HEIGHT +#define DEFAULT_HEIGHT_SEARCH 10.0f // default search distance to find height at nearby locations +#define DEFAULT_WATER_SEARCH 50.0f // default search distance to case detection water level class Creature; class Unit; @@ -43,14 +52,14 @@ class GridMap { private: - uint32 m_flags; + uint32 m_flags = 0; // Area data - uint16 m_gridArea; - uint16* m_area_map; + uint16 m_gridArea = 0; + uint16* m_area_map = nullptr; // Height level data - float m_gridHeight; + float m_gridHeight = INVALID_HEIGHT_VALUE; float m_gridIntHeightMultiplier; union { @@ -73,9 +82,9 @@ class GridMap uint8 m_liquid_width; uint8 m_liquid_height; float m_liquidLevel; - uint16* m_liquidEntry; - uint8* m_liquidFlags; - float* m_liquid_map; + uint16* m_liquidEntry = nullptr; + uint8* m_liquidFlags = nullptr; + float* m_liquid_map = nullptr; bool loadAreaData(FILE* in, uint32 offset, uint32 size); bool loadHeightData(FILE* in, uint32 offset, uint32 size); @@ -83,7 +92,7 @@ class GridMap // Get height functions and pointers typedef float(GridMap::*pGetHeightPtr)(float x, float y) const; - pGetHeightPtr m_gridGetHeight; + pGetHeightPtr m_gridGetHeight = &GridMap::getHeightFromFlat; float getHeightFromFloat(float x, float y) const; float getHeightFromUint16(float x, float y) const; float getHeightFromUint8(float x, float y) const; @@ -124,14 +133,7 @@ class Referencable Countable m_count; }; -typedef ACE_Atomic_Op AtomicLong; - -#define MAX_HEIGHT 100000.0f // can be use for find ground height at surface -#define INVALID_HEIGHT -100000.0f // for check, must be equal to VMAP_INVALID_HEIGHT, real value for unknown height is VMAP_INVALID_HEIGHT_VALUE -#define INVALID_HEIGHT_VALUE -200000.0f // for return, must be equal to VMAP_INVALID_HEIGHT_VALUE, check value for unknown height is VMAP_INVALID_HEIGHT -#define MAX_FALL_DISTANCE 250000.0f // "unlimited fall" to find VMap ground if it is available, just larger than MAX_HEIGHT - INVALID_HEIGHT -#define DEFAULT_HEIGHT_SEARCH 10.0f // default search distance to find height at nearby locations -#define DEFAULT_WATER_SEARCH 50.0f // default search distance to case detection water level +using AtomicLong = std::atomic; // class for sharing and managin GridMap objects class TerrainInfo : public Referencable @@ -196,14 +198,13 @@ class TerrainInfo : public Referencable // global garbage collection timer ShortIntervalTimer i_timer; - typedef ACE_Thread_Mutex LOCK_TYPE; - typedef ACE_Guard LOCK_GUARD; + using LOCK_TYPE = std::mutex ; + using LOCK_GUARD = std::unique_lock; LOCK_TYPE m_mutex; LOCK_TYPE m_refMutex; }; -// class for managing TerrainData object and all sort of geometry querying operations -class TerrainManager : public MaNGOS::Singleton > +class TerrainManager : public MaNGOS::Singleton > { typedef std::unordered_map TerrainDataMap; friend class MaNGOS::OperatorNew; @@ -248,7 +249,7 @@ class TerrainManager : public MaNGOS::Singleton::Lock Guard; + typedef MaNGOS::ClassLevelLockable::Lock Guard; TerrainDataMap i_TerrainMap; typedef std::vector> LiquidTypeStore; diff --git a/src/game/Maps/GridNotifiers.cpp b/src/game/Maps/GridNotifiers.cpp index 762a9818e..581e6799c 100644 --- a/src/game/Maps/GridNotifiers.cpp +++ b/src/game/Maps/GridNotifiers.cpp @@ -84,7 +84,7 @@ VisibleNotifier::Notify() // generate outOfRange for not iterate objects i_data.AddOutOfRangeGUID(i_clientGUIDs); - player.m_visibleGUIDs_lock.acquire_write(); + std::unique_lock lock(player.m_visibleGUIDs_lock); for (ObjectGuidSet::iterator itr = i_clientGUIDs.begin(); itr != i_clientGUIDs.end(); ++itr) { if (Player* targetPlayer = player.GetMap()->GetPlayer(*itr)) @@ -96,7 +96,7 @@ VisibleNotifier::Notify() DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is out of range (no in active cells set) now for %s", itr->GetString().c_str(), player.GetGuidStr().c_str()); } - player.m_visibleGUIDs_lock.release(); + lock.unlock(); if (i_data.HasData()) { diff --git a/src/game/Maps/Map.cpp b/src/game/Maps/Map.cpp index c831a1049..d8678fa20 100644 --- a/src/game/Maps/Map.cpp +++ b/src/game/Maps/Map.cpp @@ -50,6 +50,7 @@ #include "MovementBroadcaster.h" #include "PlayerBroadcaster.h" #include "GridSearchers.h" +#include "ThreadPool.h" #include "AuraRemovalMgr.h" #include "GameEventMgr.h" #include "world/world_event_wareffort.h" @@ -127,8 +128,19 @@ Map::Map(uint32 id, time_t expiry, uint32 InstanceId) m_persistentState = sMapPersistentStateMgr.AddPersistentState(i_mapEntry, GetInstanceId(), 0, IsDungeon()); m_persistentState->SetUsedByMapState(this); - m_weatherSystem = new WeatherSystem(this); + + if (IsContinent()) + { + m_motionThreads.reset(new ThreadPool(sWorld.getConfig(CONFIG_UINT32_CONTINENTS_MOTIONUPDATE_THREADS))); + m_objectThreads.reset(new ThreadPool(std::max((int)sWorld.getConfig(CONFIG_UINT32_MAP_OBJECTSUPDATE_THREADS) -1,0))); + m_visibilityThreads.reset(new ThreadPool(std::max((int)sWorld.getConfig(CONFIG_UINT32_MAP_VISIBILITYUPDATE_THREADS) -1,0))); + m_cellThreads.reset(new ThreadPool(std::max((int)sWorld.getConfig(CONFIG_UINT32_MTCELLS_THREADS) - 1, 0))); + m_visibilityThreads->start>(); + m_cellThreads->start(); + m_motionThreads->start(); + m_objectThreads->start>(); + } } // Nostalrius @@ -661,24 +673,6 @@ inline void Map::UpdateActiveCellsCallback(uint32 diff, uint32 now, uint32 threa } } -class MapAsynchCellsWorker : public ACE_Based::Runnable -{ -public: - MapAsynchCellsWorker(int i, int nthreads, uint32 _diff, uint32 _now, uint32 _step, Map* m) : threadIdx(i), nThreads(nthreads), diff(_diff), now(_now), step(_step), map(m) - { - } - - virtual void run() - { - map->UpdateActiveCellsCallback(diff, now, threadIdx, nThreads, step); - } - int threadIdx; - int nThreads; - uint32 diff, now, step; - Map* map; -}; - - inline void Map::UpdateActiveCellsAsynch(uint32 now, uint32 diff) { resetMarkedCells(); @@ -690,26 +684,17 @@ inline void Map::UpdateActiveCellsAsynch(uint32 now, uint32 diff) for (m_activeNonPlayersIter = m_activeNonPlayers.begin(); m_activeNonPlayersIter != m_activeNonPlayers.end(); ++m_activeNonPlayersIter) MarkCellsAroundObject(*m_activeNonPlayersIter); - int const nthreads = sWorld.getConfig(CONFIG_UINT32_MTCELLS_THREADS); - // Step 1 - std::vector threads; - for (int i = 0; i < (nthreads - 1); ++i) - threads.push_back(new ACE_Based::Thread(new MapAsynchCellsWorker(i, nthreads, diff, now, 0, this))); - UpdateActiveCellsCallback(diff, now, nthreads-1, nthreads, 0); - for (const auto& thread : threads) + const int nthreads = m_cellThreads->size(); + for (int step = 0; step < 2; step++) { - thread->wait(); - delete thread; - } - // Step 2 - threads.clear(); - for (int i = 0; i < (nthreads - 1); ++i) - threads.push_back(new ACE_Based::Thread(new MapAsynchCellsWorker(i, nthreads, diff, now, 1, this))); - UpdateActiveCellsCallback(diff, now, nthreads-1, nthreads, 1); - for (const auto& thread : threads) - { - thread->wait(); - delete thread; + for (int i = 0; i < nthreads; ++i) + m_cellThreads << [this, diff, now, i, nthreads](){ + UpdateActiveCellsCallback(diff, now, i, nthreads+1, 0); + }; + std::future job = m_cellThreads->processWorkload(); + UpdateActiveCellsCallback(diff, now, nthreads, nthreads+1, 0); + if (job.valid()) + job.wait(); } } @@ -737,26 +722,6 @@ inline void Map::UpdateActiveCellsSynch(uint32 now, uint32 diff) } } -class UnitsMovementUpdater : public ACE_Based::Runnable -{ -public: - UnitsMovementUpdater(int i, int nthreads, std::set& _updates, uint32 _diff) : threadIdx(i), nThreads(nthreads), updates(_updates), diff(_diff) - { - } - - virtual void run() - { - int i = 0; - for (const auto itr : updates) - if (((++i) % nThreads) == threadIdx) - if (itr->IsInWorld()) - itr->GetMotionMaster()->UpdateMotionAsync(diff); - } - int threadIdx; - int nThreads; - std::set& updates; - uint32 diff; -}; inline void Map::UpdateCells(uint32 map_diff) { @@ -767,22 +732,19 @@ inline void Map::UpdateCells(uint32 map_diff) _lastCellsUpdate = now; /// update active cells around players and active objects - if (IsContinent() && sWorld.getConfig(CONFIG_UINT32_MTCELLS_THREADS)) + if (IsContinent() && m_cellThreads->status() == ThreadPool::Status::READY) UpdateActiveCellsAsynch(now, diff); else UpdateActiveCellsSynch(now, diff); - int nthreads = sWorld.getConfig(CONFIG_UINT32_CONTINENTS_MOTIONUPDATE_THREADS); - if (IsContinent() && nthreads) + if (IsContinent() && m_motionThreads->status() == ThreadPool::Status::READY && !unitsMvtUpdate.empty()) { - std::vector threads(nthreads); - for (int i = 0; i < nthreads; ++i) - threads[i] = new ACE_Based::Thread(new UnitsMovementUpdater(i, nthreads, unitsMvtUpdate, diff)); - for (const auto& thread : threads) - { - thread->wait(); - delete thread; - } + for (std::set::iterator it = unitsMvtUpdate.begin(); it != unitsMvtUpdate.end(); it++) + m_motionThreads << [it,diff](){ + if ((*it)->IsInWorld()) + (*it)->GetMotionMaster()->UpdateMotionAsync(diff); + }; + m_motionThreads->processWorkload().wait(); } unitsMvtUpdate.clear(); } @@ -886,6 +848,7 @@ void Map::Update(uint32 t_diff) uint32 sessionsUpdateTime = WorldTimer::getMSTimeDiffToNow(updateMapTime); /// update players at tick + std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); UpdateSessionsMovementAndSpellsIfNeeded(); UpdatePlayers(); uint32 playersUpdateTime = WorldTimer::getMSTimeDiffToNow(updateMapTime) - sessionsUpdateTime; @@ -911,16 +874,13 @@ void Map::Update(uint32 t_diff) uint32 additionnalWaitTime = 0; uint32 additionnalUpdateCounts = 0; - if (_updateIdx >= 0) + if (!Instanceable()) { additionnalWaitTime = WorldTimer::getMSTime(); - sMapMgr.MarkContinentUpdateFinished(_updateIdx); - while (!sMapMgr.IsContinentUpdateFinished()) + sMapMgr.MarkContinentUpdateFinished(); + while (!sMapMgr.waitContinentUpdateFinishedUntil(start + std::chrono::milliseconds(sWorld.getConfig(CONFIG_UINT32_INTERVAL_MAPUPDATE)))) { - ACE_Based::Thread::Sleep(10); - if (sMapMgr.IsContinentUpdateFinished()) - break; - + start = std::chrono::high_resolution_clock::now(); UpdateSessionsMovementAndSpellsIfNeeded(); UpdatePlayers(); ++additionnalUpdateCounts; @@ -1658,9 +1618,8 @@ void Map::AddObjectToRemoveList(WorldObject* obj) MANGOS_ASSERT(obj->GetMapId() == GetId() && obj->GetInstanceId() == GetInstanceId()); obj->CleanupsBeforeDelete(); // remove or simplify at least cross referenced links - i_objectsToRemove_lock.acquire(); + std::unique_lock lock(i_objectsToRemove_lock); i_objectsToRemove.insert(obj); - i_objectsToRemove_lock.release(); } void Map::RemoveAllObjectsInRemoveList() @@ -1668,7 +1627,7 @@ void Map::RemoveAllObjectsInRemoveList() if (i_objectsToRemove.empty()) return; - i_objectsToRemove_lock.acquire(); + std::unique_lock lock(i_objectsToRemove_lock); while (!i_objectsToRemove.empty()) { WorldObject* obj = *i_objectsToRemove.begin(); @@ -1705,7 +1664,6 @@ void Map::RemoveAllObjectsInRemoveList() break; } } - i_objectsToRemove_lock.release(); } uint32 Map::GetPlayersCountExceptGMs() const @@ -2361,21 +2319,21 @@ void Map::ScriptsStart(ScriptMapMap const& scripts, uint32 id, WorldObject* sour ///- Schedule script execution for all scripts in the script map ScriptMap const* s2 = &(s->second); bool immedScript = false; - m_scriptSchedule_lock.acquire(); - for (const auto& iter : *s2) + + std::unique_lock lock(m_scriptSchedule_lock); + for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter) { ScriptAction sa; sa.sourceGuid = sourceGuid; sa.targetGuid = targetGuid; - sa.script = &iter.second; - m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(sWorld.GetGameTime() + iter.first), sa)); - if (iter.first == 0) + sa.script = &iter->second; + m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(sWorld.GetGameTime() + iter->first), sa)); + if (iter->first == 0) immedScript = true; sScriptMgr.IncreaseScheduledScriptsCount(); } - m_scriptSchedule_lock.release(); } void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, WorldObject* source, WorldObject* target) @@ -2391,10 +2349,9 @@ void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, WorldObject sa.targetGuid = targetGuid; sa.script = &script; - m_scriptSchedule_lock.acquire(); + std::unique_lock lock(m_scriptSchedule_lock); m_scriptSchedule.insert(ScriptScheduleMap::value_type(time_t(sWorld.GetGameTime() + delay), sa)); sScriptMgr.IncreaseScheduledScriptsCount(); - m_scriptSchedule_lock.release(); } void Map::ScriptCommandStartDirect(ScriptInfo const& script, WorldObject* source, WorldObject* target) @@ -2480,20 +2437,18 @@ void Map::TerminateScript(ScriptAction const& step) /// Process queued scripts void Map::ScriptsProcess() { - m_scriptSchedule_lock.acquire(); + std::unique_lock lock(m_scriptSchedule_lock); + if (m_scriptSchedule.empty()) - { - m_scriptSchedule_lock.release(); return; - } ///- Process overdue queued scripts ScriptScheduleMap::iterator iter = m_scriptSchedule.begin(); // ok as multimap is a *sorted* associative container while (!m_scriptSchedule.empty() && (iter->first <= sWorld.GetGameTime())) { - ScriptAction const step = iter->second; - m_scriptSchedule_lock.release(); + ScriptAction const step = iter->second; + lock.unlock(); WorldObject* source = nullptr; WorldObject* target = nullptr; @@ -2506,8 +2461,7 @@ void Map::ScriptsProcess() if (scriptResultOk) scriptResultOk = (this->*(m_ScriptCommands[step.script->command]))(*step.script, source, target); - m_scriptSchedule_lock.acquire(); - + lock.lock(); // Command returns true if we should abort script. if (scriptResultOk) TerminateScript(step); @@ -2520,9 +2474,9 @@ void Map::ScriptsProcess() sScriptMgr.DecreaseScheduledScriptCount(); } + iter = m_scriptSchedule.begin(); } - m_scriptSchedule_lock.release(); } /** @@ -2664,39 +2618,48 @@ WorldObject* Map::GetWorldObjectOrPlayer(ObjectGuid guid) return nullptr; } -class ObjectUpdatePacketBuilder : public ACE_Based::Runnable +void Map::AddUpdateObject(Object *obj) { -public: - ObjectUpdatePacketBuilder(std::set::iterator& a, std::set::iterator& b, uint32 now) : begin(a), current(a), end(b), beginTime(now) - { - } + if (_processingSendObjUpdates) + return; + std::unique_lock lock(i_objectsToClientUpdate_lock); + i_objectsToClientUpdate.insert(obj); +} - virtual void run() - { - WorldDatabase.ThreadStart(); // Not needed if we don't do SQL queries from this thread ... - DoUpdateObjects(); - WorldDatabase.ThreadEnd(); - } - void DoUpdateObjects() - { - uint32 timeout = sWorld.getConfig(CONFIG_UINT32_MAP_OBJECTSUPDATE_TIMEOUT); - UpdateDataMapType update_players; // Player -> UpdateData +void Map::RemoveUpdateObject(Object *obj) +{ + ASSERT(!_processingSendObjUpdates); + std::unique_lock lock(i_objectsToClientUpdate_lock); + i_objectsToClientUpdate.erase( obj ); +} - for (; current != end; ++current) - { - if (WorldTimer::getMSTimeDiffToNow(beginTime) > timeout) - break; - (*current)->BuildUpdateData(update_players); - } +void Map::AddRelocatedUnit(Unit *obj) +{ + if (_processingUnitsRelocation) + return; + std::unique_lock lock(i_unitsRelocated_lock); + i_unitsRelocated.insert(obj); +} + +void Map::RemoveRelocatedUnit(Unit *obj) +{ + ASSERT(!_processingUnitsRelocation); + std::unique_lock lock(i_unitsRelocated_lock); + i_unitsRelocated.erase(obj); +} + +void Map::AddUnitToMovementUpdate(Unit *unit) +{ + std::unique_lock lock(unitsMvtUpdate_lock); + unitsMvtUpdate.insert(unit); +} + +void Map::RemoveUnitFromMovementUpdate(Unit *unit) +{ + std::unique_lock lock(unitsMvtUpdate_lock); + unitsMvtUpdate.erase(unit); +} - for (auto& itr : update_players) - itr.second.Send(itr.first->GetSession()); - } - std::set::iterator begin; - std::set::iterator current; - std::set::iterator end; - uint32 beginTime; -}; //#define MAP_SENDOBJECTUPDATES_PROFILE @@ -2713,56 +2676,48 @@ void Map::SendObjectUpdates() // Compute maximum number of threads uint32 threads = 1; if (IsContinent()) - { - threads = sWorld.getConfig(CONFIG_UINT32_MAP_OBJECTSUPDATE_THREADS); - if (!threads) - threads = 1; - } + threads = m_objectThreads->size() +1; if (!_objUpdatesThreads) _objUpdatesThreads = 1; if (threads < _objUpdatesThreads) _objUpdatesThreads = threads; if (threads > objectsCount) threads = objectsCount; - uint32 step = objectsCount / threads; - ACE_Based::Thread** updaters = threads > 1 ? new ACE_Based::Thread*[threads - 1] : nullptr; - ObjectUpdatePacketBuilder** objUpdaters = new ObjectUpdatePacketBuilder*[threads]; - std::set::iterator itBegin = i_objectsToClientUpdate.begin(); - std::set::iterator itEnd = i_objectsToClientUpdate.begin(); + ASSERT(step > 0); ASSERT(threads >= 1); - for (uint32 i = 0; i < threads; ++i) - { - itBegin = itEnd; - if (i == (threads - 1)) - itEnd = i_objectsToClientUpdate.end(); - else - { - for (uint32 j = 0; j < step; ++j) - ++itEnd; - } - objUpdaters[i] = new ObjectUpdatePacketBuilder(itBegin, itEnd, now); - objUpdaters[i]->incReference(); - if (i == (threads - 1)) // Do not create a useless supplementary thread - objUpdaters[i]->DoUpdateObjects(); - else - updaters[i] = new ACE_Based::Thread(objUpdaters[i]); - } - for (uint32 i = 0; i < (threads - 1); ++i) - updaters[i]->wait(); - for (uint32 i = 0; i < threads; ++i) - { - /* std::set::erase - * Iterators, pointers and references referring to elements removed by the function are invalidated. - * All other iterators, pointers and references keep their validity. - */ - i_objectsToClientUpdate.erase(objUpdaters[i]->begin, objUpdaters[i]->current); - objUpdaters[i]->decReference(); - if (i != (threads - 1)) - delete updaters[i]; - } + std::vector::iterator> t; + t.reserve(i_objectsToClientUpdate.size()); //t will not contain end! + for (std::set::iterator it = i_objectsToClientUpdate.begin(); it != i_objectsToClientUpdate.end(); it++) + t.push_back(it); + std::atomic ait(0); + uint32 timeout = sWorld.getConfig(CONFIG_UINT32_MAP_OBJECTSUPDATE_TIMEOUT); + auto f = [&t, &ait, beginTime=now, timeout](){ + UpdateDataMapType update_players; // Player -> UpdateData + int it = ait++; + while (it < t.size()) + { + (*t[it])->BuildUpdateData(update_players); + if (WorldTimer::getMSTimeDiffToNow(beginTime) > timeout) + break; + it = ait++; + } + + for (UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter) + iter->second.Send(iter->first->GetSession()); + }; + std::future job; + if (m_objectThreads) + job = m_objectThreads->processWorkload(); + f(); + if (job.valid()) + job.wait(); + if (ait >= i_objectsToClientUpdate.size()) //ait is increased before checks, so max value is `objectsCount + threads` + i_objectsToClientUpdate.clear(); + else + i_objectsToClientUpdate.erase(t.front(), t[ait]); // If we timeout, use more threads ! if (!i_objectsToClientUpdate.empty()) @@ -2771,8 +2726,6 @@ void Map::SendObjectUpdates() --_objUpdatesThreads; _processingSendObjUpdates = false; - delete[] updaters; - delete[] objUpdaters; #ifdef MAP_SENDOBJECTUPDATES_PROFILE uint32 diff = WorldTimer::getMSTimeDiffToNow(now); if (diff > 50) @@ -2780,35 +2733,6 @@ void Map::SendObjectUpdates() #endif } -class VisibilityUpdater : public ACE_Based::Runnable -{ -public: - VisibilityUpdater(std::set::iterator& a, std::set::iterator& b, uint32 now) : begin(a), current(a), end(b), beginTime(now) - { - } - - virtual void run() - { - WorldDatabase.ThreadStart(); - DoUpdateVisibility(); - WorldDatabase.ThreadEnd(); - } - void DoUpdateVisibility() - { - uint32 timeout = sWorld.getConfig(CONFIG_UINT32_MAP_VISIBILITYUPDATE_TIMEOUT); - for (; current != end; ++current) - { - if (WorldTimer::getMSTimeDiffToNow(beginTime) > timeout) - break; - (*current)->ProcessRelocationVisibilityUpdates(); - } - } - std::set::iterator begin; - std::set::iterator current; - std::set::iterator end; - uint32 beginTime; -}; - //#define MAP_UPDATEVISIBILITY_PROFILE void Map::UpdateVisibilityForRelocations() @@ -2823,50 +2747,47 @@ void Map::UpdateVisibilityForRelocations() // Compute number of threads to spawn uint32 threads = 1; if (IsContinent()) - { - threads = sWorld.getConfig(CONFIG_UINT32_MAP_VISIBILITYUPDATE_THREADS); - if (!threads) - threads = 1; - } + threads = m_visibilityThreads->size() + 1; if (!_unitRelocationThreads) _unitRelocationThreads = 1; if (threads < _unitRelocationThreads) _unitRelocationThreads = threads; if (threads > objectsCount) threads = objectsCount; - uint32 step = objectsCount / threads; - ACE_Based::Thread** updaters = threads > 1 ? new ACE_Based::Thread*[threads - 1] : nullptr; - VisibilityUpdater** visUpdaters = new VisibilityUpdater*[threads]; - std::set::iterator itBegin = i_unitsRelocated.begin(); - std::set::iterator itEnd = i_unitsRelocated.begin(); + ASSERT(step > 0); - for (uint32 i = 0; i < threads; ++i) - { - itBegin = itEnd; - if (i == (threads - 1)) - itEnd = i_unitsRelocated.end(); - else + + std::vector::iterator> t; + t.reserve(i_unitsRelocated.size()); + for (std::set::iterator it = i_unitsRelocated.begin(); it != i_unitsRelocated.end(); it++) + t.emplace_back(it); + std::atomic ait(0); + uint32 timeout = sWorld.getConfig(CONFIG_UINT32_MAP_VISIBILITYUPDATE_TIMEOUT); + auto f = [&t, &ait, beginTime=now, timeout](){ + int it = ait++; + while (it < t.size()) { - for (uint32 j = 0; j < step; ++j) - ++itEnd; + (*t[it])->ProcessRelocationVisibilityUpdates(); + if (WorldTimer::getMSTimeDiffToNow(beginTime) > timeout) + break; + it = ait++; } - visUpdaters[i] = new VisibilityUpdater(itBegin, itEnd, now); - visUpdaters[i]->incReference(); - if (i == (threads - 1)) - visUpdaters[i]->DoUpdateVisibility(); - else - updaters[i] = new ACE_Based::Thread(visUpdaters[i]); - } - for (uint32 i = 0; i < threads - 1; ++i) - updaters[i]->wait(); - for (uint32 i = 0; i < threads; ++i) - { - i_unitsRelocated.erase(visUpdaters[i]->begin, visUpdaters[i]->current); - visUpdaters[i]->decReference(); - if (i != (threads - 1)) - delete updaters[i]; - } + }; + for (uint32 i = 0; i < threads -1; ++i) + m_visibilityThreads << f; + + std::future job; + if (m_visibilityThreads) + job = m_visibilityThreads->processWorkload(); + + f(); + if (job.valid()) + job.wait(); + if (ait >= i_unitsRelocated.size()) //ait is increased before checks, so max value is `objectsCount + threads` + i_unitsRelocated.clear(); + else + i_unitsRelocated.erase(t.front(), t[ait]); if (!i_unitsRelocated.empty()) ++_unitRelocationThreads; @@ -2874,8 +2795,6 @@ void Map::UpdateVisibilityForRelocations() --_unitRelocationThreads; _processingUnitsRelocation = false; - delete[] updaters; - delete[] visUpdaters; #ifdef MAP_UPDATEVISIBILITY_PROFILE uint32 diff = WorldTimer::getMSTimeDiffToNow(now); @@ -2888,7 +2807,7 @@ uint32 Map::GenerateLocalLowGuid(HighGuid guidhigh) { // TODOLOCK // TODO: for map local guid counters possible force reload map instead shutdown server at guid counter overflow - m_guidGenerators_lock.acquire(); + std::unique_lock lock(m_guidGenerators_lock); uint32 guid = 0; switch (guidhigh) { @@ -2907,7 +2826,6 @@ uint32 Map::GenerateLocalLowGuid(HighGuid guidhigh) default: MANGOS_ASSERT(0); } - m_guidGenerators_lock.release(); return guid; } @@ -3252,6 +3170,44 @@ VMAP::ModelInstance* Map::FindCollisionModel(float x1, float y1, float z1, float return VMAP::VMapFactory::createOrGetVMapManager()->FindCollisionModel(GetId(), x1, y1, z1, x2, y2, z2); } +void Map::RemoveGameObjectModel(const GameObjectModel &model) +{ + std::unique_lock lock(_dynamicTree_lock); + _dynamicTree.remove(model); + _dynamicTree.balance(); +} + +void Map::InsertGameObjectModel(const GameObjectModel &model) +{ + std::unique_lock lock(_dynamicTree_lock); + _dynamicTree.insert(model); + _dynamicTree.balance(); +} + +bool Map::ContainsGameObjectModel(const GameObjectModel &model) const +{ + std::shared_lock lock(_dynamicTree_lock); + return _dynamicTree.contains(model); +} + +bool Map::GetDynamicObjectHitPos(Movement::Vector3 start, Movement::Vector3 end, Movement::Vector3 &out, float finalDistMod) const +{ + std::shared_lock lock(_dynamicTree_lock); + return _dynamicTree.getObjectHitPos(start, end, out, finalDistMod); +} + +float Map::GetDynamicTreeHeight(float x, float y, float z, float maxSearchDist) const +{ + std::shared_lock lock(_dynamicTree_lock); + return _dynamicTree.getHeight(x, y, z, maxSearchDist); +} + +bool Map::CheckDynamicTreeLoS(float x1, float y1, float z1, float x2, float y2, float z2) const +{ + std::shared_lock lock(_dynamicTree_lock); + return _dynamicTree.isInLineOfSight(x1, y1, z1, x2, y2, z2); +} + void Map::CrashUnload() { @@ -3357,7 +3313,7 @@ bool Map::ShouldUpdateMap(uint32 now, uint32 inactiveTimeLimit) // in AddCorpseToRemove because it can be called concurrently. if (!update) { - ACE_Guard guard(_corpseRemovalLock); + std::unique_lock guard(_corpseRemovalLock); if (!_corpseToRemove.empty()) update = true; } @@ -3371,7 +3327,7 @@ bool Map::ShouldUpdateMap(uint32 now, uint32 inactiveTimeLimit) */ void Map::AddCorpseToRemove(Corpse* corpse, ObjectGuid looter_guid) { - ACE_Guard guard(_corpseRemovalLock); + std::unique_lock guard(_corpseRemovalLock); _corpseToRemove.emplace_back(corpse, looter_guid); } @@ -3380,7 +3336,7 @@ void Map::AddCorpseToRemove(Corpse* corpse, ObjectGuid looter_guid) */ void Map::RemoveBones(Corpse* corpse) { - ACE_Guard guard(_bonesLock); + std::unique_lock guard(_bonesLock); _bones.remove(corpse); } @@ -3389,7 +3345,7 @@ void Map::RemoveBones(Corpse* corpse) */ void Map::RemoveCorpses(bool unload) { - ACE_Guard guard(_corpseRemovalLock); + std::unique_lock guard(_corpseRemovalLock); for (auto iter = _corpseToRemove.begin(); iter != _corpseToRemove.end();) { auto corpse = iter->first; @@ -3452,7 +3408,7 @@ void Map::RemoveCorpses(bool unload) // Only take the lock for a second { - ACE_Guard guard(_bonesLock); + std::unique_lock guard(_bonesLock); _bones.push_back(bones); } } @@ -3483,7 +3439,7 @@ void Map::RemoveOldBones(uint32 const diff) _bonesCleanupTimer = 0u; time_t now = time(nullptr); - ACE_Guard guard(_bonesLock); + std::unique_lock guard(_bonesLock); for (auto iter = _bones.begin(); iter != _bones.end();) { Corpse* bones = *iter; diff --git a/src/game/Maps/Map.h b/src/game/Maps/Map.h index 6f86cf3b4..643a26761 100644 --- a/src/game/Maps/Map.h +++ b/src/game/Maps/Map.h @@ -25,8 +25,6 @@ #include "Common.h" #include "Platform/Define.h" #include "Policies/ThreadingModel.h" -#include "ace/RW_Thread_Mutex.h" -#include "ace/Thread_Mutex.h" #include "DBCStructure.h" #include "GridDefines.h" @@ -48,6 +46,8 @@ #include #include #include +#include +#include using Movement::Vector3; @@ -187,7 +187,7 @@ struct AreaLocale #define MIN_UNLOAD_DELAY 1 // immediate unload typedef std::map CreatureGroupHolderType; -typedef ACE_Thread_Mutex MapMutexType; // Use ACE_Null_Mutex to disable locks +using MapMutexType = std::mutex; // can be replaced with a null mutex // Instance IDs reserved for internal use (instanced continent parts, ...) #define RESERVED_INSTANCES_LAST 100 @@ -324,7 +324,9 @@ struct ScriptedEvent ScriptedEvent(ScriptedEvent const&) = delete; }; -class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable +class ThreadPool; + +class Map : public GridRefManager { friend class MapReference; friend class ObjectGridLoader; @@ -334,7 +336,9 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable Map(uint32 id, time_t, uint32 InstanceId); public: - ~Map() override; + Map(const Map &) = delete; + const Map & operator=(const Map &) = delete; + virtual ~Map() override; void PrintInfos(ChatHandler& handler); void SpawnActiveObjects(); // currently unused for normal maps @@ -512,68 +516,28 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable template void InsertObject(ObjectGuid const& guid, T* ptr) { - m_objectsStore_lock.acquire_write(); + std::unique_lock lock(m_objectsStore_lock); m_objectsStore.insert(guid, ptr); - m_objectsStore_lock.release(); } template void EraseObject(ObjectGuid const& guid) { - m_objectsStore_lock.acquire_write(); + std::unique_lock lock(m_objectsStore_lock); m_objectsStore.erase(guid, (T*)nullptr); - m_objectsStore_lock.release(); } template T* GetObject(ObjectGuid const& guid) { - m_objectsStore_lock.acquire_read(); - T* ptr = m_objectsStore.find(guid, (T*)nullptr); - m_objectsStore_lock.release(); - return ptr; - } - void AddUpdateObject(Object *obj) - { - if (_processingSendObjUpdates) - return; - i_objectsToClientUpdate_lock.acquire(); - i_objectsToClientUpdate.insert(obj); - i_objectsToClientUpdate_lock.release(); + std::shared_lock lock(m_objectsStore_lock); + return m_objectsStore.find(guid, (T*)nullptr); } + void AddUpdateObject(Object *obj); - void RemoveUpdateObject(Object *obj) - { - ASSERT(!_processingSendObjUpdates); - i_objectsToClientUpdate_lock.acquire(); - i_objectsToClientUpdate.erase(obj); - i_objectsToClientUpdate_lock.release(); - } + void RemoveUpdateObject(Object *obj); // May be called from a different map ... - void AddRelocatedUnit(Unit* obj) - { - if (_processingUnitsRelocation) - return; - i_unitsRelocated_lock.acquire(); - i_unitsRelocated.insert(obj); - i_unitsRelocated_lock.release(); - } - void RemoveRelocatedUnit(Unit* obj) - { - ASSERT(!_processingUnitsRelocation); - i_unitsRelocated_lock.acquire(); - i_unitsRelocated.erase(obj); - i_unitsRelocated_lock.release(); - } + void AddRelocatedUnit(Unit* obj); + void RemoveRelocatedUnit(Unit* obj); - void AddUnitToMovementUpdate(Unit* unit) - { - unitsMvtUpdate_lock.acquire(); - unitsMvtUpdate.insert(unit); - unitsMvtUpdate_lock.release(); - } - void RemoveUnitFromMovementUpdate(Unit* unit) - { - unitsMvtUpdate_lock.acquire(); - unitsMvtUpdate.erase(unit); - unitsMvtUpdate_lock.release(); - } + void AddUnitToMovementUpdate(Unit* unit); + void RemoveUnitFromMovementUpdate(Unit* unit); // DynObjects currently uint32 GenerateLocalLowGuid(HighGuid guidhigh); @@ -601,48 +565,12 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable VMAP::ModelInstance* FindCollisionModel(float x1, float y1, float z1, float x2, float y2, float z2); void Balance() { _dynamicTree.balance(); } - void RemoveGameObjectModel(GameObjectModel const& model) - { - _dynamicTree_lock.acquire_write(); - _dynamicTree.remove(model); - _dynamicTree.balance(); - _dynamicTree_lock.release(); - } - void InsertGameObjectModel(GameObjectModel const& model) - { - _dynamicTree_lock.acquire_write(); - _dynamicTree.insert(model); - _dynamicTree.balance(); - _dynamicTree_lock.release(); - } - bool ContainsGameObjectModel(GameObjectModel const& model) const - { - _dynamicTree_lock.acquire_read(); - bool r = _dynamicTree.contains(model); - _dynamicTree_lock.release(); - return r; - } - bool GetDynamicObjectHitPos(Vector3 start, Vector3 end, Vector3& out, float finalDistMod) const - { - _dynamicTree_lock.acquire_read(); - bool r = _dynamicTree.getObjectHitPos(start, end, out, finalDistMod); - _dynamicTree_lock.release(); - return r; - } - float GetDynamicTreeHeight(float x, float y, float z, float maxSearchDist) const - { - _dynamicTree_lock.acquire_read(); - float r = _dynamicTree.getHeight(x, y, z, maxSearchDist); - _dynamicTree_lock.release(); - return r; - } - bool CheckDynamicTreeLoS(float x1, float y1, float z1, float x2, float y2, float z2) const - { - _dynamicTree_lock.acquire_read(); - bool r = _dynamicTree.isInLineOfSight(x1, y1, z1, x2, y2, z2); - _dynamicTree_lock.release(); - return r; - } + void RemoveGameObjectModel(const GameObjectModel& model); + void InsertGameObjectModel(const GameObjectModel& model); + bool ContainsGameObjectModel(const GameObjectModel& model) const; + bool GetDynamicObjectHitPos(Vector3 start, Vector3 end, Vector3& out, float finalDistMod) const; + float GetDynamicTreeHeight(float x, float y, float z, float maxSearchDist) const; + bool CheckDynamicTreeLoS(float x1, float y1, float z1, float x2, float y2, float z2) const; bool IsUnloading() const { return m_unloading; } void MarkAsCrashed() { m_crashed = true; } bool IsCrashed() const { return m_crashed; } @@ -663,8 +591,6 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable */ void SetWeather(uint32 zoneId, WeatherType type, float grade, bool permanently); - void SetMapUpdateIndex(int idx) { _updateIdx = idx; } - // Get Holder for Creature Linking CreatureLinkingHolder* GetCreatureLinkingHolder() { return &m_creatureLinkingHolder; } @@ -717,17 +643,17 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable void SendObjectUpdates(); void UpdateVisibilityForRelocations(); - bool _processingSendObjUpdates; - uint32 _objUpdatesThreads; - mutable MapMutexType i_objectsToClientUpdate_lock; + bool _processingSendObjUpdates = false; + uint32 _objUpdatesThreads = 0; + mutable std::mutex i_objectsToClientUpdate_lock; std::set i_objectsToClientUpdate; - bool _processingUnitsRelocation; - uint32 _unitRelocationThreads; - mutable MapMutexType i_unitsRelocated_lock; + bool _processingUnitsRelocation = false; + uint32 _unitRelocationThreads = 0; + mutable std::mutex i_unitsRelocated_lock; std::set i_unitsRelocated; - mutable MapMutexType unitsMvtUpdate_lock; + mutable std::mutex unitsMvtUpdate_lock; std::set unitsMvtUpdate; mutable MapMutexType _corpseRemovalLock; @@ -741,18 +667,23 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable void RemoveCorpses(bool unload = false); void RemoveOldBones(uint32 const diff); + std::unique_ptr m_objectThreads; + std::unique_ptr m_motionThreads; + std::unique_ptr m_visibilityThreads; + std::unique_ptr m_cellThreads; + protected: MapEntry const* i_mapEntry; uint32 i_id; uint32 i_InstanceId; - uint32 m_unloadTimer; + uint32 m_unloadTimer = 0; float m_VisibleDistance; float m_GridActivationDistance; - mutable ACE_RW_Mutex _dynamicTree_lock; + mutable std::shared_timed_mutex _dynamicTree_lock; DynamicMapTree _dynamicTree; - MapPersistentState* m_persistentState; + MapPersistentState* m_persistentState = nullptr; MapRefManager m_mapRefManager; MapRefManager::iterator m_mapRefIter; @@ -762,18 +693,18 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable ActiveNonPlayers::iterator m_activeNonPlayersIter; typedef TypeUnorderedMapContainer MapStoredObjectTypesContainer; - ACE_RW_Mutex m_objectsStore_lock; + mutable std::shared_timed_mutex m_objectsStore_lock; MapStoredObjectTypesContainer m_objectsStore; // Objects that must update even in inactive grids without activating them typedef std::set TransportsContainer; TransportsContainer _transports; TransportsContainer::iterator _transportsUpdateIter; - bool m_unloading; - bool m_crashed; - bool m_updateFinished; + bool m_unloading = false; + bool m_crashed = false; + bool m_updateFinished = false; uint32 m_updateDiffMod; - uint32 m_lastMvtSpellsUpdate; + uint32 m_lastMvtSpellsUpdate = 0; private: time_t i_gridExpiry; @@ -785,18 +716,18 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable std::bitset marked_cells; - mutable MapMutexType i_objectsToRemove_lock; - std::set i_objectsToRemove; + mutable std::mutex i_objectsToRemove_lock; + std::set i_objectsToRemove; typedef std::multimap ScriptScheduleMap; - MapMutexType m_scriptSchedule_lock; + mutable MapMutexType m_scriptSchedule_lock; ScriptScheduleMap m_scriptSchedule; - InstanceData* i_data; - uint32 i_script_id; + InstanceData* i_data = nullptr; + uint32 i_script_id = 0; // Map local low guid counters - mutable MapMutexType m_guidGenerators_lock; + mutable std::mutex m_guidGenerators_lock; ObjectGuidGenerator m_CreatureGuids; ObjectGuidGenerator m_GameObjectGuids; ObjectGuidGenerator m_DynObjectGuids; @@ -809,10 +740,10 @@ class Map : public GridRefManager, public MaNGOS::ObjectLevelLockable template void RemoveFromGrid(T*, NGridType*, Cell const&); // Custom - uint32 _lastMapUpdate; - uint32 _lastPlayerLeftTime; + uint32 _lastMapUpdate = 0; + uint32 _lastPlayerLeftTime = 0; uint32 _lastPlayersUpdate; - uint32 _inactivePlayersSkippedUpdates; + uint32 _inactivePlayersSkippedUpdates = 0; uint32 _lastCellsUpdate; int8 _updateIdx; diff --git a/src/game/Maps/MapManager.cpp b/src/game/Maps/MapManager.cpp index e5273ef69..02234f077 100644 --- a/src/game/Maps/MapManager.cpp +++ b/src/game/Maps/MapManager.cpp @@ -31,21 +31,21 @@ #include "ObjectMgr.h" #include "ZoneScriptMgr.h" #include "Map.h" +#include "ThreadPool.h" +#include "MoveMap.h" -typedef MaNGOS::ClassLevelLockable MapManagerLock; +typedef MaNGOS::ClassLevelLockable MapManagerLock; INSTANTIATE_SINGLETON_2(MapManager, MapManagerLock); -INSTANTIATE_CLASS_MUTEX(MapManager, ACE_Recursive_Thread_Mutex); +INSTANTIATE_CLASS_MUTEX(MapManager, std::recursive_mutex); MapManager::MapManager() - : - i_GridStateErrorCount(0), + : i_gridCleanUpDelay(sWorld.getConfig(CONFIG_UINT32_INTERVAL_GRIDCLEAN)), i_MaxInstanceId(RESERVED_INSTANCES_LAST), - i_maxContinentThread(0), - i_continentUpdateFinished(nullptr), - asyncMapUpdating(false) + m_threads(new ThreadPool(sWorld.getConfig(CONFIG_UINT32_MAPUPDATE_INSTANCED_UPDATE_THREADS))) { i_timer.SetInterval(sWorld.getConfig(CONFIG_UINT32_INTERVAL_MAPUPDATE)); + m_threads->start>(); } MapManager::~MapManager() @@ -233,55 +233,6 @@ void MapManager::DeleteInstance(uint32 mapid, uint32 instanceId) } } -class MapAsyncUpdater : public ACE_Based::Runnable -{ -public: - MapAsyncUpdater(bool* updFinished, uint32 updateDiff) : - updateFinished(updFinished), diff(updateDiff), loops(0) - { - } - - virtual void run() - { - WorldDatabase.ThreadStart(); - do - { - for (const auto& map : maps) - { - if (loops && *updateFinished) - break; - map->DoUpdate(diff); - } - if (!(*updateFinished)) - ACE_Based::Thread::Sleep(5); - ++loops; - } - while (!(*updateFinished)); - WorldDatabase.ThreadEnd(); - } - std::vector maps; - volatile bool* updateFinished; - uint32 diff; - uint32 loops; -}; - -class ContinentAsyncUpdater : public ACE_Based::Runnable -{ -public: - ContinentAsyncUpdater(uint32 updateDiff, Map* m) : map(m), diff(updateDiff) - { - } - - virtual void run() - { - WorldDatabase.ThreadStart(); - map->DoUpdate(diff); - WorldDatabase.ThreadEnd(); - } - Map* map; - uint32 diff; -}; - void MapManager::Update(uint32 diff) { i_timer.Update(diff); @@ -293,73 +244,72 @@ void MapManager::Update(uint32 diff) ExecuteDelayedPlayerTeleports(); uint32 mapsDiff = (uint32)i_timer.GetCurrent(); - bool updateFinished = false; asyncMapUpdating = true; - std::vector instanceUpdaters(sWorld.getConfig(CONFIG_UINT32_MAPUPDATE_INSTANCED_UPDATE_THREADS)); - std::vector continentsUpdaters; - for (auto& instanceUpdater : instanceUpdaters) - instanceUpdater = new MapAsyncUpdater(&updateFinished, mapsDiff); // Will be deleted at thread end - int mapIdx = 0; int continentsIdx = 0; uint32 now = WorldTimer::getMSTime(); + uint32 inactiveTimeLimit = sWorld.getConfig(CONFIG_UINT32_EMPTY_MAPS_UPDATE_TIME); - for (const auto& itr : i_maps) + std::vector> continentsUpdaters; + std::vector> instancesUpdaters; + + for (MapMapType::iterator iter = i_maps.begin(); iter != i_maps.end(); ++iter) { // If this map has been empty for too long, we no longer update it. - if (!itr.second->ShouldUpdateMap(now, inactiveTimeLimit)) + if (!iter->second->ShouldUpdateMap(now, inactiveTimeLimit)) continue; - itr.second->UpdateSync(mapsDiff); - itr.second->MarkNotUpdated(); - itr.second->SetMapUpdateIndex(-1); - if (itr.second->Instanceable()) + iter->second->UpdateSync(mapsDiff); + iter->second->MarkNotUpdated(); + if (iter->second->Instanceable()) { - if (!instanceUpdaters.empty()) - { - instanceUpdaters[mapIdx % instanceUpdaters.size()]->maps.push_back(itr.second); - ++mapIdx; - } + if (m_threads->status() == ThreadPool::Status::READY) + instancesUpdaters.emplace_back([iter,mapsDiff](){ + iter->second->DoUpdate(mapsDiff); + }); else - itr.second->Update(mapsDiff); + iter->second->DoUpdate(mapsDiff); } else // One threat per continent part { - itr.second->SetMapUpdateIndex(continentsIdx++); - ContinentAsyncUpdater* task = new ContinentAsyncUpdater(mapsDiff, itr.second); - continentsUpdaters.push_back(task); + continentsUpdaters.emplace_back([iter,mapsDiff](){ + Map *m = iter->second; + if (!m->IsUpdateFinished() || !sMapMgr.IsContinentUpdateFinished()) + m->DoUpdate(mapsDiff); + }); + continentsIdx++; } } i_maxContinentThread = continentsIdx; - i_continentUpdateFinished = new volatile bool[i_maxContinentThread]; - for (int i = 0; i < i_maxContinentThread; ++i) - i_continentUpdateFinished[i] = false; - std::vector asyncUpdateThreads(instanceUpdaters.size() + continentsUpdaters.size()); + i_continentUpdateFinished.store(0); - for (int tid = 0; tid < instanceUpdaters.size(); ++tid) - asyncUpdateThreads[tid] = new ACE_Based::Thread(instanceUpdaters[tid]); - for (int tid = 0; tid < continentsUpdaters.size(); ++tid) - asyncUpdateThreads[tid + instanceUpdaters.size()] = new ACE_Based::Thread(continentsUpdaters[tid]); - - // Finish continents updating - for (int tid = instanceUpdaters.size(); tid < asyncUpdateThreads.size(); ++tid) + if (!m_continentThreads || m_continentThreads->size() < continentsUpdaters.size()) { - asyncUpdateThreads[tid]->wait(); - delete asyncUpdateThreads[tid]; + m_continentThreads.reset(new ThreadPool(continentsUpdaters.size())); + m_continentThreads->start<>(); } + std::future continents = m_continentThreads->processWorkload(std::move(continentsUpdaters), + ThreadPool::Callable()); - updateFinished = true; SwitchPlayersInstances(); - // And then instances updating - for (int tid = 0; tid < instanceUpdaters.size(); ++tid) - { - asyncUpdateThreads[tid]->wait(); - delete asyncUpdateThreads[tid]; - } - delete[] i_continentUpdateFinished; - i_continentUpdateFinished = nullptr; + std::chrono::high_resolution_clock::time_point start; + do { + start = std::chrono::high_resolution_clock::now(); + std::future f = m_threads->processWorkload(instancesUpdaters, + ThreadPool::Callable()); + + if (f.valid()) + f.wait(); + else + break; + }while(!sMapMgr.waitContinentUpdateFinishedUntil(start + std::chrono::milliseconds(sWorld.getConfig(CONFIG_UINT32_INTERVAL_MAPUPDATE)))); + + + if (continents.valid()) + continents.wait(); + asyncMapUpdating = false; // Execute far teleports after all map updates have finished @@ -668,7 +618,7 @@ uint32 MapManager::GetContinentInstanceId(uint32 mapId, float x, float y, bool* -6308.63f, -3049.32f, -6107.82f, -3345.30f, -6008.49f, -3590.52f, - -5989.37f, -4312.29f, + -5989.37f, -4312.29f, -5806.26f, -5864.11f }; static float const stormwindAreaNorthLimit[] = { @@ -879,7 +829,7 @@ void MapManager::ScheduleFarTeleport(Player* player, ScheduledTeleportData* data } else { - ACE_Guard guard(m_scheduledFarTeleportsLock); + std::unique_lock guard(m_scheduledFarTeleportsLock); player->SetPendingFarTeleport(true); m_scheduledFarTeleports[player] = data; } @@ -902,7 +852,7 @@ void MapManager::ExecuteDelayedPlayerTeleports() // player logout and login). void MapManager::ExecuteSingleDelayedTeleport(Player* player) { - ACE_Guard guard(m_scheduledFarTeleportsLock); + std::unique_lock guard(m_scheduledFarTeleportsLock); ScheduledTeleportMap::iterator iter = m_scheduledFarTeleports.find(player); if (iter != m_scheduledFarTeleports.end()) @@ -926,7 +876,7 @@ void MapManager::ExecuteSingleDelayedTeleport(ScheduledTeleportMap::iterator ite void MapManager::CancelDelayedPlayerTeleport(Player* player) { - ACE_Guard guard(m_scheduledFarTeleportsLock); + std::unique_lock guard(m_scheduledFarTeleportsLock); ScheduledTeleportMap::iterator iter = m_scheduledFarTeleports.find(player); if (iter != m_scheduledFarTeleports.end()) @@ -942,9 +892,8 @@ void MapManager::ScheduleInstanceSwitch(Player* player, uint16 newInstance) { uint8 mapId = player->GetMap()->GetId(); ASSERT(mapId < LAST_CONTINENT_ID); - m_scheduledInstanceSwitches_lock[mapId].acquire(); + std::unique_lock lock(m_scheduledInstanceSwitches_lock[mapId]); m_scheduledInstanceSwitches[mapId][player] = newInstance; - m_scheduledInstanceSwitches_lock[mapId].release(); } void MapManager::SwitchPlayersInstances() @@ -961,3 +910,29 @@ void MapManager::SwitchPlayersInstances() m_scheduledInstanceSwitches[continent].clear(); } } + +void MapManager::MarkContinentUpdateFinished() +{ + ASSERT(i_continentUpdateFinished < i_maxContinentThread); + std::unique_lock lock(m_continentMutex); + i_continentUpdateFinished++; + if (IsContinentUpdateFinished()) + m_continentCV.notify_all(); +} + +bool MapManager::IsContinentUpdateFinished() const +{ + return i_continentUpdateFinished == i_maxContinentThread; +} + +bool MapManager::waitContinentUpdateFinishedFor(std::chrono::milliseconds time) const +{ + std::unique_lock lock(m_continentMutex); + return m_continentCV.wait_for(lock,time,std::bind(&MapManager::IsContinentUpdateFinished,this)); +} + +bool MapManager::waitContinentUpdateFinishedUntil(std::chrono::high_resolution_clock::time_point time) const +{ + std::unique_lock lock(m_continentMutex); + return m_continentCV.wait_until(lock,time,std::bind(&MapManager::IsContinentUpdateFinished,this)); +} diff --git a/src/game/Maps/MapManager.h b/src/game/Maps/MapManager.h index d97409bbb..624d52a79 100644 --- a/src/game/Maps/MapManager.h +++ b/src/game/Maps/MapManager.h @@ -25,8 +25,6 @@ #include "Common.h" #include "Platform/Define.h" #include "Policies/Singleton.h" -#include "ace/Recursive_Thread_Mutex.h" -#include "ace/Thread_Mutex.h" #include "Map.h" #include "GridStates.h" @@ -74,15 +72,16 @@ struct MapID uint32 nInstanceId; }; +class ThreadPool; struct ScheduledTeleportData; -class MapManager : public MaNGOS::Singleton > +class MapManager : public MaNGOS::Singleton > { friend class MaNGOS::OperatorNew; - typedef ACE_Recursive_Thread_Mutex LOCK_TYPE; - typedef ACE_Guard LOCK_TYPE_GUARD; - typedef MaNGOS::ClassLevelLockable::Lock Guard; + using LOCK_TYPE = std::recursive_mutex; + using LOCK_TYPE_GUARD = std::unique_lock; + typedef MaNGOS::ClassLevelLockable::Lock Guard; public: typedef std::map MapMapType; @@ -184,31 +183,18 @@ class MapManager : public MaNGOS::Singleton i_continentUpdateFinished{0}; + + std::unique_ptr m_threads; + std::unique_ptr m_continentThreads; + bool asyncMapUpdating = false; // Instanced continent zones const static int LAST_CONTINENT_ID = 2; - ACE_Thread_Mutex m_scheduledInstanceSwitches_lock[LAST_CONTINENT_ID]; + std::mutex m_scheduledInstanceSwitches_lock[LAST_CONTINENT_ID]; std::map m_scheduledInstanceSwitches[LAST_CONTINENT_ID]; // 2 continents - ACE_Thread_Mutex m_scheduledFarTeleportsLock; + std::mutex m_scheduledFarTeleportsLock; typedef std::map ScheduledTeleportMap; ScheduledTeleportMap m_scheduledFarTeleports; diff --git a/src/game/Maps/MapPersistentStateMgr.h b/src/game/Maps/MapPersistentStateMgr.h index 1c0364502..eeb023ebe 100644 --- a/src/game/Maps/MapPersistentStateMgr.h +++ b/src/game/Maps/MapPersistentStateMgr.h @@ -25,7 +25,6 @@ #include "Common.h" #include "Platform/Define.h" #include "Policies/Singleton.h" -#include "ace/Thread_Mutex.h" #include #include #include @@ -317,7 +316,7 @@ class DungeonResetScheduler ResetTimeQueue m_resetTimeQueue; }; -class MapPersistentStateManager : public MaNGOS::Singleton > +class MapPersistentStateManager : public MaNGOS::Singleton > { friend class DungeonResetScheduler; public: // constructors diff --git a/src/game/Maps/MoveMap.cpp b/src/game/Maps/MoveMap.cpp index aec291bff..5c41a5238 100644 --- a/src/game/Maps/MoveMap.cpp +++ b/src/game/Maps/MoveMap.cpp @@ -57,14 +57,13 @@ MMapManager::~MMapManager() bool MMapManager::loadMapData(uint32 mapId) { - loadedMMaps_lock.acquire_read(); + std::shared_lock rlock(loadedMMaps_lock); // we already have this map loaded? if (loadedMMaps.find(mapId) != loadedMMaps.end()) { - loadedMMaps_lock.release(); return true; } - loadedMMaps_lock.release(); + rlock.unlock(); if (!sWorld.getConfig(CONFIG_BOOL_MMAP_ENABLED)) return false; @@ -105,12 +104,11 @@ bool MMapManager::loadMapData(uint32 mapId) MMapData* mmap_data = new MMapData(mesh); mmap_data->mmapLoadedTiles.clear(); - loadedMMaps_lock.acquire_write(); + std::unique_lock wlock(loadedMMaps_lock); if (loadedMMaps.find(mapId) == loadedMMaps.end()) loadedMMaps.insert(std::pair(mapId, mmap_data)); else delete mmap_data; - loadedMMaps_lock.release(); return true; } @@ -127,14 +125,14 @@ bool MMapManager::loadMap(uint32 mapId, int32 x, int32 y) return false; // get this mmap data - loadedMMaps_lock.acquire_read(); + std::shared_lock rlock(loadedMMaps_lock); MMapData* mmap = loadedMMaps[mapId]; - loadedMMaps_lock.release(); + rlock.unlock(); MANGOS_ASSERT(mmap->navMesh); // check if we already have this tile loaded uint32 packedGridPos = packTileID(x, y); - ACE_Guard guard(mmap->tilesLoading_lock); + std::unique_lock wlock(mmap->tilesLoading_lock); if (mmap->mmapLoadedTiles.find(packedGridPos) != mmap->mmapLoadedTiles.end()) return false; @@ -281,7 +279,7 @@ bool MMapManager::unloadMap(uint32 mapId) return true; } -bool MMapManager::unloadMapInstance(uint32 mapId, uint32 instanceId) +bool MMapManager::unloadMapInstance(uint32 mapId, std::thread::id instanceId) { // check if we have this map loaded if (loadedMMaps.find(mapId) == loadedMMaps.end()) @@ -320,16 +318,16 @@ dtNavMeshQuery const* MMapManager::GetNavMeshQuery(uint32 mapId) if (loadedMMaps.find(mapId) == loadedMMaps.end()) return nullptr; - uint32 tid = (uintptr_t) ACE_Based::Thread::currentId(); + std::thread::id tid= std::this_thread::get_id(); MMapData* mmap = loadedMMaps[mapId]; - mmap->navMeshQueries_lock.acquire_read(); + std::shared_lock lock(mmap->navMeshQueries_lock); NavMeshQuerySet::iterator it = mmap->navMeshQueries.find(tid); dtNavMeshQuery* navMeshQuery = nullptr; if (it == mmap->navMeshQueries.end()) { - mmap->navMeshQueries_lock.release(); - mmap->navMeshQueries_lock.acquire_write(); + lock.unlock(); + std::unique_lock ulock(mmap->navMeshQueries_lock); // allocate mesh query navMeshQuery = dtAllocNavMeshQuery(); @@ -337,18 +335,17 @@ dtNavMeshQuery const* MMapManager::GetNavMeshQuery(uint32 mapId) dtStatus dtResult = navMeshQuery->init(mmap->navMesh, 2048); if (dtStatusFailed(dtResult)) { - mmap->navMeshQueries_lock.release(); + ulock.unlock(); dtFreeNavMeshQuery(navMeshQuery); sLog.outError("MMAP:GetNavMeshQuery: Failed to initialize dtNavMeshQuery for mapId %03u thread %u", mapId, tid); return nullptr; } DETAIL_LOG("MMAP:GetNavMeshQuery: created dtNavMeshQuery for mapId %03u thread %u", mapId, tid); - mmap->navMeshQueries.insert(std::pair(tid, navMeshQuery)); + mmap->navMeshQueries.insert(std::pair(tid, navMeshQuery)); } else navMeshQuery = it->second; - mmap->navMeshQueries_lock.release(); return navMeshQuery; } @@ -425,11 +422,11 @@ dtNavMeshQuery const* MMapManager::GetModelNavMeshQuery(uint32 displayId) if (loadedModels.find(displayId) == loadedModels.end()) return nullptr; - uint32 tid = (uintptr_t) ACE_Based::Thread::currentId(); + std::thread::id tid = std::this_thread::get_id(); MMapData* mmap = loadedModels[displayId]; if (mmap->navMeshQueries.find(tid) == mmap->navMeshQueries.end()) { - ACE_Guard g(lockForModels); + std::unique_lock g(lockForModels); if (mmap->navMeshQueries.find(tid) == mmap->navMeshQueries.end()) { // allocate mesh query @@ -443,7 +440,7 @@ dtNavMeshQuery const* MMapManager::GetModelNavMeshQuery(uint32 displayId) } DETAIL_LOG("MMAP:GetNavMeshQuery: created dtNavMeshQuery for displayid %03u tid %u", displayId, tid); - mmap->navMeshQueries.insert(std::pair(tid, query)); + mmap->navMeshQueries.insert(std::pair(tid, query)); } } diff --git a/src/game/Maps/MoveMap.h b/src/game/Maps/MoveMap.h index 3786aaa38..7a63bde1c 100644 --- a/src/game/Maps/MoveMap.h +++ b/src/game/Maps/MoveMap.h @@ -19,9 +19,6 @@ #ifndef _MOVE_MAP_H #define _MOVE_MAP_H -#include -#include -#include #include "Platform/CompilerDefs.h" #include "Platform/Define.h" @@ -31,6 +28,9 @@ #include "Detour/Include/DetourNavMesh.h" #include "Detour/Include/DetourNavMeshQuery.h" +#include +#include + // memory management inline void* dtCustomAlloc(size_t size, dtAllocHint /*hint*/) { @@ -46,7 +46,7 @@ inline void dtCustomFree(void* ptr) namespace MMAP { typedef std::unordered_map MMapTileSet; - typedef std::unordered_map NavMeshQuerySet; + typedef std::unordered_map NavMeshQuerySet; // dummy struct to hold map's mmap data struct MMapData @@ -65,9 +65,9 @@ namespace MMAP // we have to use single dtNavMeshQuery for every instance, since those are not thread safe NavMeshQuerySet navMeshQueries; // threadId to query - ACE_RW_Mutex navMeshQueries_lock; + std::shared_timed_mutex navMeshQueries_lock; MMapTileSet mmapLoadedTiles; // maps [map grid coords] to [dtTile] - ACE_Thread_Mutex tilesLoading_lock; + std::mutex tilesLoading_lock; }; typedef std::unordered_map MMapDataSet; @@ -84,7 +84,7 @@ namespace MMAP bool loadGameObject(uint32 displayId); bool unloadMap(uint32 mapId, int32 x, int32 y); bool unloadMap(uint32 mapId); - bool unloadMapInstance(uint32 mapId, uint32 instanceId); + bool unloadMapInstance(uint32 mapId, std::thread::id instanceId); // The returned [dtNavMeshQuery const*] is NOT threadsafe // Returns a NavMeshQuery valid for current thread only. @@ -99,10 +99,11 @@ namespace MMAP static uint32 packTileID(int32 x, int32 y); MMapDataSet loadedMMaps; - ACE_RW_Mutex loadedMMaps_lock; + std::shared_timed_mutex loadedMMaps_lock; MMapDataSet loadedModels; + uint32 loadedTiles; - ACE_Thread_Mutex lockForModels; + std::mutex lockForModels; }; // static class diff --git a/src/game/Maps/PathFinder.cpp b/src/game/Maps/PathFinder.cpp index 42d96f244..b954177be 100644 --- a/src/game/Maps/PathFinder.cpp +++ b/src/game/Maps/PathFinder.cpp @@ -348,7 +348,7 @@ void PathInfo::BuildPolyPath(Vector3 const& startPos, Vector3 const& endPos) // free and invalidate old path data clear(); - //unsigned int const threadId = (uintptr_t) ACE_Based::Thread::currentId(); + // std::thread::id const threadId = std::this_thread::get_id(); //if (threadId != m_navMeshQuery->m_owningThread) //sLog.outError("CRASH: We are using a dtNavMeshQuery from thread %u which belongs to thread %u!", threadId, m_navMeshQuery->m_owningThread); diff --git a/src/game/Movement/MotionMaster.cpp b/src/game/Movement/MotionMaster.cpp index 395b6be40..69b272d42 100644 --- a/src/game/Movement/MotionMaster.cpp +++ b/src/game/Movement/MotionMaster.cpp @@ -777,8 +777,8 @@ bool MotionMaster::GetDestination(float &x, float &y, float &z) // 2017-09-16 02:06:32 Targeted UpdateAsync::Acquiring movespline lock for Unit Pet (Petnumber: 93 Guid: 22) in map (0, 6) thread 11156 // 2017-09-16 02:06:32 MotionMaster::Acquiring movespline lock for Unit Pet (Petnumber: 87 Guid :21) in map (0, 6) thread 11156 - ACE_Guard guard(m_owner->asyncMovesplineLock, false); - if (!guard.locked()) + std::unique_lock guard(m_owner->asyncMovesplineLock, std::try_to_lock); + if (!guard.owns_lock()) return false; if (m_owner->movespline->Finalized()) diff --git a/src/game/Movement/RandomMovementGenerator.cpp b/src/game/Movement/RandomMovementGenerator.cpp index c7e7f2fbf..e4913c1d1 100644 --- a/src/game/Movement/RandomMovementGenerator.cpp +++ b/src/game/Movement/RandomMovementGenerator.cpp @@ -114,7 +114,7 @@ bool RandomMovementGenerator::Update(Creature &creature, uint32 const& diff) void RandomMovementGenerator::UpdateAsync(Creature &creature, uint32 diff) { // Lock async updates for safety, see Unit::asyncMovesplineLock doc - ACE_Guard guard(creature.asyncMovesplineLock); + std::unique_lock guard(creature.asyncMovesplineLock); if (creature.HasUnitState(UNIT_STAT_CAN_NOT_MOVE | UNIT_STAT_DISTRACTED)) { i_nextMoveTime.Reset(0); // Expire the timer diff --git a/src/game/Movement/TargetedMovementGenerator.cpp b/src/game/Movement/TargetedMovementGenerator.cpp index c6edf8f95..b888e987d 100644 --- a/src/game/Movement/TargetedMovementGenerator.cpp +++ b/src/game/Movement/TargetedMovementGenerator.cpp @@ -231,7 +231,7 @@ void TargetedMovementGeneratorMedium::UpdateAsync(T &owner, uint32 /*diff* return; // Lock async updates for safety, see Unit::asyncMovesplineLock doc - ACE_Guard guard(owner.asyncMovesplineLock); + std::unique_lock guard(owner.asyncMovesplineLock); _setTargetLocation(owner); } diff --git a/src/game/ObjectAccessor.cpp b/src/game/ObjectAccessor.cpp index 45027ad7c..60d9a0c45 100644 --- a/src/game/ObjectAccessor.cpp +++ b/src/game/ObjectAccessor.cpp @@ -36,9 +36,9 @@ #include -typedef MaNGOS::ClassLevelLockable ObjectAccessorLock; +typedef MaNGOS::ClassLevelLockable ObjectAccessorLock; INSTANTIATE_SINGLETON_2(ObjectAccessor, ObjectAccessorLock); -INSTANTIATE_CLASS_MUTEX(ObjectAccessor, ACE_Thread_Mutex); +INSTANTIATE_CLASS_MUTEX(ObjectAccessor, std::mutex); ObjectAccessor::ObjectAccessor() {} ObjectAccessor::~ObjectAccessor() @@ -329,7 +329,7 @@ void ObjectAccessor::RemoveObject(MasterPlayer* player) /// Define the static member of HashMapHolder template typename HashMapHolder::MapType HashMapHolder::m_objectMap; -template ACE_RW_Thread_Mutex HashMapHolder::i_lock; +template std::shared_timed_mutex HashMapHolder::i_lock; /// Global definitions for the hashmap storage diff --git a/src/game/ObjectAccessor.h b/src/game/ObjectAccessor.h index bebe282f1..6bbc088db 100644 --- a/src/game/ObjectAccessor.h +++ b/src/game/ObjectAccessor.h @@ -25,8 +25,6 @@ #include "Common.h" #include "Platform/Define.h" #include "Policies/Singleton.h" -#include -#include #include "Policies/ThreadingModel.h" #include "UpdateData.h" @@ -52,9 +50,9 @@ class HashMapHolder public: typedef std::unordered_map MapType; - typedef ACE_RW_Thread_Mutex LockType; - typedef ACE_Read_Guard ReadGuard; - typedef ACE_Write_Guard WriteGuard; + typedef std::shared_timed_mutex LockType; + typedef std::shared_lock ReadGuard; + typedef std::unique_lock WriteGuard; static void Insert(T* o) { @@ -88,7 +86,7 @@ class HashMapHolder static MapType m_objectMap; }; -class ObjectAccessor : public MaNGOS::Singleton > +class ObjectAccessor : public MaNGOS::Singleton > { friend class MaNGOS::OperatorNew; @@ -159,8 +157,8 @@ class ObjectAccessor : public MaNGOS::Singleton Guard; + using LockType = std::mutex; + using Guard = MaNGOS::GeneralLock; LockType i_playerGuard; LockType i_corpseGuard; diff --git a/src/game/ObjectGuid.h b/src/game/ObjectGuid.h index 950b82aaf..b87d21090 100644 --- a/src/game/ObjectGuid.h +++ b/src/game/ObjectGuid.h @@ -26,8 +26,6 @@ #include #include -#include "ace/Thread_Mutex.h" - #include "Common.h" #include "ByteBuffer.h" @@ -322,8 +320,8 @@ public: ObjectGuidGenerator::GenerateRange(first, last); } protected: - typedef ACE_Thread_Mutex LockType; - typedef MaNGOS::GeneralLock Guard; + using LockType = std::mutex; + using Guard = MaNGOS::GeneralLock; LockType lock; }; diff --git a/src/game/ObjectMgr.cpp b/src/game/ObjectMgr.cpp index 0c5deb02e..ecbeecd84 100644 --- a/src/game/ObjectMgr.cpp +++ b/src/game/ObjectMgr.cpp @@ -2025,10 +2025,9 @@ void ObjectMgr::AddCreatureToGrid(uint32 guid, CreatureData const* data) CellPair cell_pair = MaNGOS::ComputeCellPair(data->position.x, data->position.y); uint32 cell_id = (cell_pair.y_coord * TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord; - m_MapObjectGuids_lock.acquire(); + std::unique_lock lock(m_MapObjectGuids_lock); CellObjectGuids& cell_guids = m_MapObjectGuids[data->position.mapId][cell_id]; cell_guids.creatures.insert(guid); - m_MapObjectGuids_lock.release(); } void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data) @@ -2036,10 +2035,9 @@ void ObjectMgr::RemoveCreatureFromGrid(uint32 guid, CreatureData const* data) CellPair cell_pair = MaNGOS::ComputeCellPair(data->position.x, data->position.y); uint32 cell_id = (cell_pair.y_coord * TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord; - m_MapObjectGuids_lock.acquire(); + std::unique_lock lock(m_MapObjectGuids_lock); CellObjectGuids& cell_guids = m_MapObjectGuids[data->position.mapId][cell_id]; cell_guids.creatures.erase(guid); - m_MapObjectGuids_lock.release(); } void ObjectMgr::LoadGameobjects(bool reload) @@ -2201,10 +2199,9 @@ void ObjectMgr::AddGameobjectToGrid(uint32 guid, GameObjectData const* data) CellPair cell_pair = MaNGOS::ComputeCellPair(data->position.x, data->position.y); uint32 cell_id = (cell_pair.y_coord * TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord; - m_MapObjectGuids_lock.acquire(); + std::unique_lock lock(m_MapObjectGuids_lock); CellObjectGuids& cell_guids = m_MapObjectGuids[data->position.mapId][cell_id]; cell_guids.gameobjects.insert(guid); - m_MapObjectGuids_lock.release(); } void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data) @@ -2212,10 +2209,9 @@ void ObjectMgr::RemoveGameobjectFromGrid(uint32 guid, GameObjectData const* data CellPair cell_pair = MaNGOS::ComputeCellPair(data->position.x, data->position.y); uint32 cell_id = (cell_pair.y_coord * TOTAL_NUMBER_OF_CELLS_PER_MAP) + cell_pair.x_coord; - m_MapObjectGuids_lock.acquire(); + std::unique_lock lock(m_MapObjectGuids_lock); CellObjectGuids& cell_guids = m_MapObjectGuids[data->position.mapId][cell_id]; cell_guids.gameobjects.erase(guid); - m_MapObjectGuids_lock.release(); } // In order to keep database item template data correct for each patch, fix changed spell effects used by some items here. @@ -7950,10 +7946,9 @@ void ObjectMgr::DeleteGOData(uint32 guid) void ObjectMgr::AddCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid, uint32 instance) { // corpses are always added to spawn mode 0 and they are spawned by their instance id - m_MapObjectGuids_lock.acquire(); + std::unique_lock lock(m_MapObjectGuids_lock); CellObjectGuids& cell_guids = m_MapObjectGuids[mapid][cellid]; cell_guids.corpses[player_guid] = instance; - m_MapObjectGuids_lock.release(); } void ObjectMgr::DeleteCorpseCellData(uint32 mapid, uint32 cellid, uint32 player_guid) @@ -11234,4 +11229,4 @@ void ObjectMgr::ApplyPremadeSpecTemplateToPlayer(uint32 entry, Player* pPlayer) pPlayer->LearnSpell(spellId, false, (firstRankId == spellId && GetTalentSpellPos(firstRankId))); } } -} \ No newline at end of file +} diff --git a/src/game/ObjectMgr.h b/src/game/ObjectMgr.h index 8e587936c..56b9c8c24 100644 --- a/src/game/ObjectMgr.h +++ b/src/game/ObjectMgr.h @@ -1116,12 +1116,11 @@ class ObjectMgr // global grid objects state (static DB spawns, global spawn mods from gameevent system) CellObjectGuids const& GetCellObjectGuids(uint16 mapid, uint32 cell_id) { - m_MapObjectGuids_lock.acquire(); + std::unique_lock lock(m_MapObjectGuids_lock); CellObjectGuids const& guids = m_MapObjectGuids[mapid][cell_id]; - m_MapObjectGuids_lock.release(); return guids; } - ACE_Thread_Mutex& GetCellLoadingObjectsMutex() // TODO: Mutex per cell? + std::mutex& GetCellLoadingObjectsMutex() // TODO: Mutex per cell? { return m_MapObjectGuids_lock; } @@ -1505,11 +1504,12 @@ class ObjectMgr FishingBaseSkillMap m_FishingBaseSkillMap; typedef std::map > HalfNameMap; + HalfNameMap m_PetHalfNameMap0; HalfNameMap m_PetHalfNameMap1; MapObjectGuids m_MapObjectGuids; - ACE_Thread_Mutex m_MapObjectGuids_lock; + std::mutex m_MapObjectGuids_lock; CreatureDataMap m_CreatureDataMap; CreatureLocaleMap m_CreatureLocaleMap; diff --git a/src/game/Objects/GameObject.cpp b/src/game/Objects/GameObject.cpp index 527c2f3f4..89305dd1a 100644 --- a/src/game/Objects/GameObject.cpp +++ b/src/game/Objects/GameObject.cpp @@ -665,7 +665,7 @@ void GameObject::Refresh() void GameObject::AddUniqueUse(Player* player) { - ACE_Guard guard(m_UniqueUsers_lock); + std::unique_lock guard(m_UniqueUsers_lock); AddUse(); @@ -677,7 +677,7 @@ void GameObject::AddUniqueUse(Player* player) m_UniqueUsers.insert(player->GetObjectGuid()); - guard.release(); + guard.unlock(); if (GameObjectInfo const* info = GetGOInfo()) if (info->type == GAMEOBJECT_TYPE_SUMMONING_RITUAL && @@ -700,7 +700,7 @@ void GameObject::AddUniqueUse(Player* player) void GameObject::RemoveUniqueUse(Player* player) { - ACE_Guard guard(m_UniqueUsers_lock); + const std::lock_guard guard(m_UniqueUsers_lock); auto itr = m_UniqueUsers.find(player->GetObjectGuid()); if (itr == m_UniqueUsers.end()) @@ -729,7 +729,7 @@ void GameObject::RemoveUniqueUse(Player* player) void GameObject::FinishRitual() { - ACE_Guard guard(m_UniqueUsers_lock); + std::unique_lock guard(m_UniqueUsers_lock); if (GameObjectInfo const* info = GetGOInfo()) { @@ -748,7 +748,7 @@ void GameObject::FinishRitual() { std::advance(it, urand(0, m_UniqueUsers.size() - 1)); - guard.release(); + guard.unlock(); if (Player* target = GetMap()->GetPlayer(*it)) target->CastSpell(target, spellid, true); @@ -759,13 +759,13 @@ void GameObject::FinishRitual() bool GameObject::HasUniqueUser(Player* player) { - ACE_Guard guard(m_UniqueUsers_lock); + const std::lock_guard guard(m_UniqueUsers_lock); return m_UniqueUsers.find(player->GetObjectGuid()) != m_UniqueUsers.end(); } uint32 GameObject::GetUniqueUseCount() { - ACE_Guard guard(m_UniqueUsers_lock); + const std::lock_guard guard(m_UniqueUsers_lock); return m_UniqueUsers.size(); } diff --git a/src/game/Objects/GameObject.h b/src/game/Objects/GameObject.h index 2221b408d..4abee65ca 100644 --- a/src/game/Objects/GameObject.h +++ b/src/game/Objects/GameObject.h @@ -27,7 +27,6 @@ #include "Object.h" #include "LootMgr.h" #include "Database/DatabaseEnv.h" -#include #include "Util.h" // GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push,N), also any gcc version not support it at some platform @@ -883,7 +882,7 @@ class GameObject : public WorldObject // collected only for GAMEOBJECT_TYPE_SUMMONING_RITUAL ObjectGuid m_firstUser; // first GO user, in most used cases owner, but in some cases no, for example non-summoned multi-use GAMEOBJECT_TYPE_SUMMONING_RITUAL GuidsSet m_UniqueUsers; // all players who use item, some items activated after specific amount unique uses - ACE_Thread_Mutex m_UniqueUsers_lock; + std::mutex m_UniqueUsers_lock; ObjectGuid m_summonTarget; // The player who is being summoned uint64 m_rotation; diff --git a/src/game/Objects/Object.cpp b/src/game/Objects/Object.cpp index 2ae7d9c36..dabe5f9ae 100644 --- a/src/game/Objects/Object.cpp +++ b/src/game/Objects/Object.cpp @@ -605,9 +605,8 @@ void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, UpdateMask* u } if (isType(TYPEMASK_GAMEOBJECT)) { - target->m_visibleGobjsQuestAct_lock.acquire(); + std::unique_lock lock(target->m_visibleGobjsQuestAct_lock); target->m_visibleGobjQuestActivated[GetObjectGuid()] = IsActivateToQuest; - target->m_visibleGobjsQuestAct_lock.release(); } MANGOS_ASSERT(updateMask && updateMask->GetCount() == m_valuesCount); diff --git a/src/game/Objects/Player.cpp b/src/game/Objects/Player.cpp index dada9f0b9..dca2c4437 100644 --- a/src/game/Objects/Player.cpp +++ b/src/game/Objects/Player.cpp @@ -18497,9 +18497,9 @@ void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* targe ObjectGuid t_guid = target->GetObjectGuid(); target->DestroyForPlayer(this); - m_visibleGUIDs_lock.acquire_write(); + std::unique_lock lock(m_visibleGUIDs_lock); m_visibleGUIDs.erase(t_guid); - m_visibleGUIDs_lock.release(); + lock.unlock(); if (Player* plTarget = target->ToPlayer()) if (plTarget->m_broadcaster) @@ -18515,9 +18515,9 @@ void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* targe target->SendCreateUpdateToPlayer(this); if (target->GetTypeId() != TYPEID_GAMEOBJECT || !((GameObject*)target)->IsTransport()) { - m_visibleGUIDs_lock.acquire_write(); + std::unique_lock lock(m_visibleGUIDs_lock); m_visibleGUIDs.insert(target->GetObjectGuid()); - m_visibleGUIDs_lock.release(); + lock.unlock(); if (Player* plTarget = target->ToPlayer()) if (plTarget->m_broadcaster) @@ -18581,9 +18581,9 @@ void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateD ObjectGuid t_guid = target->GetObjectGuid(); target->BuildOutOfRangeUpdateBlock(&data); - m_visibleGUIDs_lock.acquire_write(); + std::unique_lock lock(m_visibleGUIDs_lock); m_visibleGUIDs.erase(t_guid); - m_visibleGUIDs_lock.release(); + lock.unlock(); RemoveBroadcastListener(target, this); DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is out of range for %s. Distance = %f", t_guid.GetString().c_str(), GetGuidStr().c_str(), GetDistance(target)); @@ -18595,9 +18595,9 @@ void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateD { visibleNow.insert(target); target->BuildCreateUpdateBlockForPlayer(&data, this); - m_visibleGUIDs_lock.acquire_write(); + std::unique_lock lock(m_visibleGUIDs_lock); UpdateVisibilityOf_helper(m_visibleGUIDs, target); - m_visibleGUIDs_lock.release(); + lock.unlock(); AddBroadcastListener(target, this); DEBUG_FILTER_LOG(LOG_FILTER_VISIBILITY_CHANGES, "%s is visible now for %s. Distance = %f", target->GetGuidStr().c_str(), GetGuidStr().c_str(), GetDistance(target)); @@ -19227,7 +19227,7 @@ void Player::UpdateForQuestWorldObjects() uint32 count = 0; UpdateData upd; - m_visibleGUIDs_lock.acquire_read(); + std::shared_lock lock(m_visibleGUIDs_lock); for (const auto& guid : m_visibleGUIDs) { if (guid.IsGameObject()) @@ -19241,7 +19241,7 @@ void Player::UpdateForQuestWorldObjects() } } } - m_visibleGUIDs_lock.release(); + lock.unlock(); if (count) upd.Send(GetSession()); } @@ -21541,9 +21541,8 @@ bool Player::IsInVisibleList(WorldObject const* u) const { if (u == this) return true; - m_visibleGUIDs_lock.acquire_read(); + std::shared_lock lock(m_visibleGUIDs_lock); bool atClient = m_visibleGUIDs.find(u->GetObjectGuid()) != m_visibleGUIDs.end(); - m_visibleGUIDs_lock.release(); return atClient; } @@ -21823,4 +21822,4 @@ void Player::RemoveSpellLockout(SpellSchoolMask spellSchoolMask, std::setId, this); } -} \ No newline at end of file +} diff --git a/src/game/Objects/Player.h b/src/game/Objects/Player.h index e3ba39ad5..6bfb37342 100644 --- a/src/game/Objects/Player.h +++ b/src/game/Objects/Player.h @@ -1838,9 +1838,9 @@ class Player final: public Unit // currently visible objects at player client ObjectGuidSet m_visibleGUIDs; - mutable ACE_Thread_Mutex m_visibleGUIDs_lock; + mutable std::shared_timed_mutex m_visibleGUIDs_lock; std::map m_visibleGobjQuestActivated; - mutable ACE_Thread_Mutex m_visibleGobjsQuestAct_lock; + mutable std::mutex m_visibleGobjsQuestAct_lock; bool IsInVisibleList(WorldObject const* u) const; bool IsInVisibleList_Unsafe(WorldObject const* u) const { return this == u || m_visibleGUIDs.find(u->GetObjectGuid()) != m_visibleGUIDs.end(); } diff --git a/src/game/Objects/Unit.h b/src/game/Objects/Unit.h index 99dbadf97..46e7eebd8 100644 --- a/src/game/Objects/Unit.h +++ b/src/game/Objects/Unit.h @@ -1095,7 +1095,7 @@ class Unit : public WorldObject Unit* GetTauntTarget() const; void TauntApply(Unit* pVictim); void TauntFadeOut(Unit* taunter); - + // Threat related methods bool CanHaveThreatList() const; bool IsSecondaryThreatTarget() const; @@ -1408,7 +1408,7 @@ class Unit : public WorldObject // Serialize access to the movespline to prevent thread race conditions in async // move spline updates (one thread updates a spline, while another checks the // spline for end point with targeted move gen) - ACE_Thread_Mutex asyncMovesplineLock; + std::mutex asyncMovesplineLock; void OnRelocated(); void ProcessRelocationVisibilityUpdates(); diff --git a/src/game/PacketBroadcast/MovementBroadcaster.cpp b/src/game/PacketBroadcast/MovementBroadcaster.cpp index 5c92377fe..4bfdec264 100644 --- a/src/game/PacketBroadcast/MovementBroadcaster.cpp +++ b/src/game/PacketBroadcast/MovementBroadcaster.cpp @@ -23,7 +23,7 @@ void MovementBroadcaster::StartThreads() ASSERT(m_threads.empty()); // Create new mutex vector - can't resize a vector of locks (non-copyable) - std::vector locks(m_num_threads); + std::vector locks(m_num_threads); m_thread_locks = std::move(locks); m_thread_players.resize(m_num_threads); m_thread_update_stats.resize(m_num_threads); @@ -31,8 +31,17 @@ void MovementBroadcaster::StartThreads() m_stop = false; // start the workers - for (std::size_t i = 0; i < m_num_threads; ++i) - m_threads.push_back(new ACE_Based::Thread(new MovementBroadcasterWorker(i, this))); + for (std::size_t i = 0; i < m_num_threads; ++i) { + auto mb = new MovementBroadcasterWorker(i, this); + m_threads.emplace_back(new std::thread( + [mb, i](){mb->run(); + }),[mb](std::thread *thread) { + if (thread->joinable()) + thread->join(); + delete thread; + delete mb; + }); + } } @@ -42,7 +51,7 @@ void MovementBroadcaster::RegisterPlayer(std::shared_ptr cons return; std::size_t index = player->GetGUID().GetRawValue() % m_num_threads; - ACE_Guard guard(m_thread_locks[index]); + std::unique_lock guard(m_thread_locks[index]); m_thread_players[index].insert(player); } @@ -52,7 +61,7 @@ void MovementBroadcaster::RemovePlayer(std::shared_ptr const& return; std::size_t index = player->GetGUID().GetRawValue() % m_num_threads; - ACE_Guard guard(m_thread_locks[index]); + std::unique_lock guard(m_thread_locks[index]); auto it = m_thread_players[index].find(player); if (it != m_thread_players[index].end()) @@ -86,7 +95,7 @@ void MovementBroadcaster::Work(std::size_t thread_id) else stats.slow_instance = -1; - ACE_Based::Thread::Sleep(m_sleep_timer.count()); + std::this_thread::sleep_for(m_sleep_timer); } } @@ -94,7 +103,7 @@ uint32 MovementBroadcaster::IdentifySlowMap(std::size_t thread_id) { std::map map_packets; - ACE_Guard guard(m_thread_locks[thread_id]); + std::unique_lock guard(m_thread_locks[thread_id]); for (auto& player : m_thread_players[thread_id]) map_packets[player->instanceId] += player->lastUpdatePackets; @@ -116,7 +125,7 @@ void MovementBroadcaster::BroadcastPackets(std::size_t index, uint32& num_packet { PlayersBCastSet my_players; { - ACE_Guard guard(m_thread_locks[index]); + std::unique_lock guard(m_thread_locks[index]); my_players = m_thread_players[index]; } @@ -130,15 +139,6 @@ void MovementBroadcaster::Stop() m_stop = true; - for (auto& thread : m_threads) - { - if (thread) - { - thread->wait(); - thread->destroy(); - delete thread; - } - } m_threads.clear(); } diff --git a/src/game/PacketBroadcast/MovementBroadcaster.h b/src/game/PacketBroadcast/MovementBroadcaster.h index 7fb872fc7..c7bf766a2 100644 --- a/src/game/PacketBroadcast/MovementBroadcaster.h +++ b/src/game/PacketBroadcast/MovementBroadcaster.h @@ -3,7 +3,6 @@ #include "Log.h" #include "ObjectGuid.h" -#include "Threading.h" #include #include #include @@ -13,11 +12,12 @@ #include #include #include +#include class PlayerBroadcaster; class MovementBroadcaster; -class MovementBroadcasterWorker : public ACE_Based::Runnable +class MovementBroadcasterWorker { public: MovementBroadcasterWorker(int threadId, MovementBroadcaster* broadcaster) : m_threadId(threadId), m_broadcaster(broadcaster) {}; @@ -34,11 +34,11 @@ class MovementBroadcaster final std::size_t m_num_threads; std::atomic_bool m_stop; - std::vector m_threads; + std::vector>> m_threads; std::chrono::milliseconds m_sleep_timer; std::vector m_thread_players; - std::vector m_thread_locks; + std::vector m_thread_locks; void Work(std::size_t thread_id); void BroadcastPackets(std::size_t index, uint32& num_packets); diff --git a/src/game/PacketBroadcast/PlayerBroadcaster.cpp b/src/game/PacketBroadcast/PlayerBroadcaster.cpp index f73ed9051..3a18a6255 100644 --- a/src/game/PacketBroadcast/PlayerBroadcaster.cpp +++ b/src/game/PacketBroadcast/PlayerBroadcaster.cpp @@ -31,20 +31,20 @@ void PlayerBroadcaster::AddListener(Player const* player) if (player->GetObjectGuid() == m_self) return; - ACE_Guard guard(m_listeners_lock); + const std::lock_guard guard(m_listeners_lock); m_listeners[player->GetObjectGuid()] = player->m_broadcaster; } void PlayerBroadcaster::RemoveListener(Player const* player) { ASSERT(player); - ACE_Guard guard(m_listeners_lock); + const std::lock_guard guard(m_listeners_lock); m_listeners.erase(player->GetObjectGuid()); } void PlayerBroadcaster::ClearListeners() { - ACE_Guard guard(m_listeners_lock); + const std::lock_guard guard(m_listeners_lock); m_listeners.clear(); } @@ -59,9 +59,9 @@ void PlayerBroadcaster::ProcessQueue(uint32& num_packets) if (m_queue.empty()) return; - ACE_Guard q_g(m_queue_lock), v_g(m_listeners_lock); + std::unique_lock q_g(m_queue_lock), v_g(m_listeners_lock); auto queue = std::move(m_queue); - q_g.release(); + q_g.unlock(); lastUpdatePackets = queue.size() * m_listeners.size(); num_packets += lastUpdatePackets; @@ -89,7 +89,7 @@ void PlayerBroadcaster::QueuePacket(WorldPacket packet, bool self, ObjectGuid ex data.sendToSelf = self; data.except = except; - ACE_Guard guard(m_queue_lock); + std::unique_lock guard(m_queue_lock); // We need to drop a packet here - if possible if (m_queue.size() >= MAX_QUEUE_SIZE) @@ -98,7 +98,7 @@ void PlayerBroadcaster::QueuePacket(WorldPacket packet, bool self, ObjectGuid ex if (CanSkipPacket(last_in_queue.packet.GetOpcode()) && CanSkipPacket(packet.GetOpcode())) { m_queue[m_queue.size() - 1] = std::move(data); - guard.release(); + guard.unlock(); return; } } @@ -119,7 +119,7 @@ void PlayerBroadcaster::FreeAtLogout() m_socket->RemoveReference(); m_socket = nullptr; } - ACE_Guard q_g(m_queue_lock), v_g(m_listeners_lock); + const std::lock_guard q_g(m_queue_lock), v_g(m_listeners_lock); m_queue.clear(); m_listeners.clear(); } diff --git a/src/game/PacketBroadcast/PlayerBroadcaster.h b/src/game/PacketBroadcast/PlayerBroadcaster.h index efd2556e3..a1640bcc8 100644 --- a/src/game/PacketBroadcast/PlayerBroadcaster.h +++ b/src/game/PacketBroadcast/PlayerBroadcaster.h @@ -6,7 +6,6 @@ #include "WorldSocket.h" #include "WorldPacket.h" #include "Opcodes.h" -#include #include #include #include @@ -30,8 +29,8 @@ class PlayerBroadcaster final std::map > m_listeners; std::vector m_queue; - ACE_Thread_Mutex m_listeners_lock; - ACE_Thread_Mutex m_queue_lock; + std::mutex m_listeners_lock; + std::mutex m_queue_lock; void ProcessQueue(uint32& num_packets); void SendPacket(WorldPacket const& packet); diff --git a/src/game/Protocol/WorldSocket.cpp b/src/game/Protocol/WorldSocket.cpp index f1d764e04..d46bcaec3 100644 --- a/src/game/Protocol/WorldSocket.cpp +++ b/src/game/Protocol/WorldSocket.cpp @@ -40,7 +40,7 @@ int WorldSocket::ProcessIncoming(WorldPacket* new_pct) MANGOS_ASSERT(new_pct); // manage memory ;) - ACE_Auto_Ptr aptr(new_pct); + std::unique_ptr aptr(new_pct); const ACE_UINT16 opcode = new_pct->GetOpcode(); @@ -76,7 +76,7 @@ int WorldSocket::ProcessIncoming(WorldPacket* new_pct) return HandleAuthSession(*new_pct); default: { - ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1); + GuardType lock(m_SessionLock); if (m_Session != nullptr) { @@ -363,7 +363,7 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket) if (max_count && m_OverSpeedPings > max_count) { - ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1); + GuardType lock(m_SessionLock); if (m_Session && m_Session->GetSecurity() == SEC_PLAYER) { @@ -381,7 +381,7 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket) // critical section { - ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1); + GuardType lock(m_SessionLock); #if SUPPORTED_CLIENT_BUILD > CLIENT_BUILD_1_8_4 if (m_Session) diff --git a/src/game/Protocol/WorldSocketMgr.h b/src/game/Protocol/WorldSocketMgr.h index 216121c17..4525112c3 100644 --- a/src/game/Protocol/WorldSocketMgr.h +++ b/src/game/Protocol/WorldSocketMgr.h @@ -29,6 +29,8 @@ #define __WORLDSOCKETMGR_H #include "MangosSocketMgr.h" +#include "ace/Singleton.h" +#include "ace/Thread_Mutex.h" class WorldSocket; /// Manages all sockets connected to peers and network threads diff --git a/src/game/ScriptMgr.h b/src/game/ScriptMgr.h index ddd2e80a9..417418ff2 100644 --- a/src/game/ScriptMgr.h +++ b/src/game/ScriptMgr.h @@ -24,8 +24,8 @@ #include "Policies/Singleton.h" #include "ObjectGuid.h" #include "DBCEnums.h" +#include #include "SpellDefines.h" -#include "ace/Atomic_Op.h" struct AreaTriggerEntry; class Aura; @@ -1432,7 +1432,7 @@ class ScriptMgr EscortDataMap m_mEscortDataMap; // Des donnees pour les quetes d'escorte scriptees via la DB //atomic op counter for active scripts amount - ACE_Atomic_Op m_scheduledScripts; + std::atomic m_scheduledScripts; }; #define sScriptMgr MaNGOS::Singleton::Instance() diff --git a/src/game/SocialMgr.cpp b/src/game/SocialMgr.cpp index 0380eb040..a62066cee 100644 --- a/src/game/SocialMgr.cpp +++ b/src/game/SocialMgr.cpp @@ -286,7 +286,7 @@ void SocialMgr::BroadcastToFriendListers(MasterPlayer* player, WorldPacket* pack AccountTypes gmLevelInWhoList = AccountTypes(sWorld.getConfig(CONFIG_UINT32_GM_LEVEL_IN_WHO_LIST)); bool allowTwoSideWhoList = sWorld.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST); - ACE_Guard guard(_socialMapLock); + std::unique_lock guard(_socialMapLock); for (const auto& itr : m_socialMap) { PlayerSocialMap::const_iterator itr2 = itr.second.m_playerSocialMap.find(guid); @@ -307,8 +307,8 @@ void SocialMgr::BroadcastToFriendListers(MasterPlayer* player, WorldPacket* pack PlayerSocial* SocialMgr::LoadFromDB(QueryResult* result, ObjectGuid guid) { - ACE_Guard guard(_socialMapLock); - PlayerSocial* social = &m_socialMap[guid.GetCounter()]; + std::unique_lock guard(_socialMapLock); + PlayerSocial *social = &m_socialMap[guid.GetCounter()]; social->SetPlayerGuid(guid); if (!result) @@ -345,6 +345,6 @@ PlayerSocial* SocialMgr::LoadFromDB(QueryResult* result, ObjectGuid guid) void SocialMgr::RemovePlayerSocial(uint32 guid) { - ACE_Guard guard(_socialMapLock); + std::unique_lock guard(_socialMapLock); m_socialMap.erase(guid); } diff --git a/src/game/SocialMgr.h b/src/game/SocialMgr.h index 1f1d4afef..e53658094 100644 --- a/src/game/SocialMgr.h +++ b/src/game/SocialMgr.h @@ -157,7 +157,7 @@ class SocialMgr private: SocialMap m_socialMap; - ACE_Thread_Mutex _socialMapLock; + std::mutex _socialMapLock; }; #define sSocialMgr MaNGOS::Singleton::Instance() diff --git a/src/game/Spells/SpellAuras.cpp b/src/game/Spells/SpellAuras.cpp index 2d7ccb2f1..e73776b3f 100644 --- a/src/game/Spells/SpellAuras.cpp +++ b/src/game/Spells/SpellAuras.cpp @@ -5022,8 +5022,8 @@ void Aura::HandleRangedAmmoHaste(bool apply, bool /*Real*/) { if (GetTarget()->GetTypeId() != TYPEID_PLAYER) return; - - // Quivers should not increase attack speed for ranged weapons which do not require any ammo. + + // Quivers should not increase attack speed for ranged weapons which do not require any ammo. Item* ranged_weapon = GetTarget()->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED); if (!ranged_weapon || ranged_weapon->GetProto()->AmmoType == 0) return; diff --git a/src/game/World.cpp b/src/game/World.cpp index 1ebb76655..ac3a1e4a7 100644 --- a/src/game/World.cpp +++ b/src/game/World.cpp @@ -77,6 +77,7 @@ #include "MovementBroadcaster.h" #include "HonorMgr.h" #include "Anticheat/Anticheat.h" +#include "ThreadPool.h" #include "AuraRemovalMgr.h" #include "InstanceStatistics.h" #include "GuardMgr.h" @@ -112,20 +113,23 @@ World& GetSWorld() } /// World constructor -World::World() +World::World(): + m_playerLimit(0), + m_allowMovement(true), + m_gameTime(time(nullptr)), + m_timeZoneOffset(0), + m_gameDay((m_gameTime + m_timeZoneOffset) / DAY), + m_startTime(m_gameTime), + m_wowPatch(WOW_PATCH_102), + m_defaultDbcLocale(LOCALE_enUS), + m_timeRate(1.0f) { - m_playerLimit = 0; m_ShutdownMask = 0; m_ShutdownTimer = 0; - m_gameTime = time(nullptr); - m_timeZoneOffset = 0; - m_gameDay = (m_gameTime + m_timeZoneOffset) / DAY; - m_startTime = m_gameTime; m_maxActiveSessionCount = 0; m_maxQueuedSessionCount = 0; m_MaintenanceTimeChecker = 0; m_anticrashRearmTimer = 0; - m_wowPatch = WOW_PATCH_102; m_defaultDbcLocale = LOCALE_enUS; m_availableDbcLocaleMask = 0; @@ -165,8 +169,9 @@ World::~World() if (m_charDbWorkerThread) { - m_charDbWorkerThread->wait(); - delete m_charDbWorkerThread; + if (m_charDbWorkerThread->joinable()) + m_charDbWorkerThread->join(); + m_charDbWorkerThread.reset(nullptr); } //TODO free addSessQueue } @@ -175,9 +180,9 @@ void World::Shutdown() { sPlayerBotMgr.DeleteAll(); sWorld.KickAll(); // save and kick all players - sWorld.UpdateSessions(1); // real players unload required UpdateSessions call - if (m_charDbWorkerThread) - m_charDbWorkerThread->wait(); + sWorld.UpdateSessions(1); // real players unload required UpdateSessions call + if (m_charDbWorkerThread && m_charDbWorkerThread->joinable()) + m_charDbWorkerThread->join(); } /// Find a session by its id @@ -870,7 +875,7 @@ void World::LoadConfigSettings(bool reload) VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS); VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight); - VMAP::VMapFactory::createOrGetVMapManager()->setDisableModelUnload(disableModelUnload); + VMAP::VMapFactory::createOrGetVMapManager()->setUseManagedPtrs(!disableModelUnload); VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str()); sLog.outString("WORLD: VMap support included. LineOfSight:%i, getHeight:%i, indoorCheck:%i", enableLOS, enableHeight, getConfig(CONFIG_BOOL_VMAP_INDOOR_CHECK) ? 1 : 0); sLog.outString("WORLD: VMap data directory is: %svmaps", m_dataPath.c_str()); @@ -1143,27 +1148,19 @@ void World::LoadConfigSettings(bool reload) sLog.InitSmartlogGuids(sConfig.GetStringDefault("Smartlog.ExtraGuids", "")); } -class CharactersDatabaseWorkerThread : public ACE_Based::Runnable +void charactersDatabaseWorkerThread() { -public: - CharactersDatabaseWorkerThread() + CharacterDatabase.ThreadStart(); + while (!sWorld.IsStopped()) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + if (CharacterDatabase.HasAsyncQuery()) + continue; + Player::DeleteOldCharacters(); + sObjectMgr.ReturnOrDeleteOldMails(true); } - - virtual void run() - { - CharacterDatabase.ThreadStart(); - while (!sWorld.IsStopped()) - { - ACE_Based::Thread::Sleep(1000); - if (CharacterDatabase.HasAsyncQuery()) - continue; - Player::DeleteOldCharacters(); - sObjectMgr.ReturnOrDeleteOldMails(true); - } - CharacterDatabase.ThreadEnd(); - } -}; + CharacterDatabase.ThreadEnd(); +} char const* World::GetPatchName() const { @@ -1765,7 +1762,7 @@ void World::SetInitialWorldSettings() std::make_unique(sWorld.getConfig(CONFIG_UINT32_PACKET_BCAST_THREADS), std::chrono::milliseconds(sWorld.getConfig(CONFIG_UINT32_PACKET_BCAST_FREQUENCY))); - m_charDbWorkerThread = new ACE_Based::Thread(new CharactersDatabaseWorkerThread()); + m_charDbWorkerThread.reset(new std::thread(&charactersDatabaseWorkerThread)); sLog.outString(); sLog.outString("=========================================================="); @@ -1824,30 +1821,13 @@ void World::DetectDBCLang() sLog.outString(); } -class WorldAsyncTasksExecutor : public ACE_Based::Runnable -{ -public: - WorldAsyncTasksExecutor() {} - void run() - { - WorldDatabase.ThreadStart(); - AsyncTask* task; - while (sWorld.GetNextAsyncTask(task)) - { - task->run(); - delete task; - } - WorldDatabase.ThreadEnd(); - } -}; - /// Update the World ! void World::Update(uint32 diff) { m_currentMSTime = WorldTimer::getMSTime(); m_currentTime = std::chrono::time_point_cast(Clock::now()); m_currentDiff = diff; - + ///- Update the different timers for (auto& timer : m_timers) { @@ -1893,11 +1873,22 @@ void World::Update(uint32 diff) ///- Update objects (maps, transport, creatures,...) uint32 updateMapSystemTime = WorldTimer::getMSTime(); - int threadsCount = getConfig(CONFIG_UINT32_ASYNC_TASKS_THREADS_COUNT); - std::vector asyncTaskThreads(threadsCount); - for (int i = 0; i < threadsCount; ++i) - asyncTaskThreads[i] = new ACE_Based::Thread(new WorldAsyncTasksExecutor()); - + + //TODO: find a better place for this + if (!m_updateThreads) + { + m_updateThreads = std::unique_ptr( new ThreadPool( + getConfig(CONFIG_UINT32_ASYNC_TASKS_THREADS_COUNT), + ThreadPool::ClearMode::UPPON_COMPLETION) + ); + m_updateThreads->start>(); + } + std::unique_lock lock(m_asyncTaskQueueMutex); + _asyncTasks.swap(_asyncTasksBusy); + std::future job = m_updateThreads->processWorkload(_asyncTasksBusy); + _asyncTasks.clear(); + lock.unlock(); + sMapMgr.Update(diff); sBattleGroundMgr.Update(diff); sLFGMgr.Update(diff); @@ -1916,11 +1907,9 @@ void World::Update(uint32 diff) } uint32 asyncWaitBegin = WorldTimer::getMSTime(); - for (int i = 0; i < threadsCount; ++i) - { - asyncTaskThreads[i]->wait(); - delete asyncTaskThreads[i]; - } + + if (job.valid()) + job.wait(); updateMapSystemTime = WorldTimer::getMSTimeDiffToNow(updateMapSystemTime); if (getConfig(CONFIG_UINT32_PERFLOG_SLOW_MAPSYSTEM_UPDATE) && updateMapSystemTime > getConfig(CONFIG_UINT32_PERFLOG_SLOW_MAPSYSTEM_UPDATE)) @@ -2859,7 +2848,12 @@ void World::SetSessionDisconnected(WorldSession* sess) m_disconnectedSessions.insert(sess); } -void World::LogMoneyTrade(ObjectGuid sender, ObjectGuid receiver, uint32 amount, char const* type, uint32 dataInt) +void World::AddAsyncTask(std::function task) { + std::lock_guard lock(m_asyncTaskQueueMutex); + _asyncTasks.push_back(task); +} + +void World::LogMoneyTrade(ObjectGuid sender, ObjectGuid receiver, uint32 amount, const char* type, uint32 dataInt) { if (!LogsDatabase || !sWorld.getConfig(CONFIG_BOOL_LOGSDB_TRADES)) return; @@ -3023,7 +3017,7 @@ time_t World::GetWorldUpdateTimerInterval(WorldTimers timer) return m_timers[timer].GetInterval(); } -void SessionPacketSendTask::run() +void SessionPacketSendTask::operator()() { if (WorldSession* session = sWorld.FindSession(m_accountId)) { diff --git a/src/game/World.h b/src/game/World.h index 00dddc35f..bc6347ebe 100644 --- a/src/game/World.h +++ b/src/game/World.h @@ -30,8 +30,7 @@ #include "Timer.h" #include "Policies/Singleton.h" #include "SharedDefines.h" -#include "ace/Atomic_Op.h" -#include "Commands/Nostalrius.h" +#include "Nostalrius.h" #include "ObjectGuid.h" #include "Chat/AbstractPlayer.h" #include "WorldPacket.h" @@ -42,6 +41,7 @@ #include #include #include +#include class Object; class WorldSession; @@ -636,18 +636,12 @@ enum RealmZone REALM_ZONE_CN9 = 29 // basic-Latin at create, any at login }; -class AsyncTask -{ -public: - virtual ~AsyncTask() {} - virtual void run() = 0; -}; - -class SessionPacketSendTask : public AsyncTask +class SessionPacketSendTask { + SessionPacketSendTask(const SessionPacketSendTask&) = delete; public: SessionPacketSendTask(uint32 accountId, WorldPacket& data) : m_accountId(accountId), m_data(data) {} - void run() override; + void operator ()(); private: uint32 m_accountId; WorldPacket m_data; @@ -698,6 +692,8 @@ struct CliCommandHolder ~CliCommandHolder() { delete[] m_command; } }; +class ThreadPool; + /// The World class World { @@ -875,9 +871,10 @@ class World * The tasks will be executed *while* maps are updated. So don't touch the mobs, pets, etc ... * includes reading, unless the read itself is serialized */ - void AddAsyncTask(AsyncTask* task) { _asyncTasks.add(task); } - bool GetNextAsyncTask(AsyncTask*& task) { return _asyncTasks.next(task); } - ACE_Based::LockedQueue _asyncTasks; + void AddAsyncTask(std::function task); + std::mutex m_asyncTaskQueueMutex; + std::vector> _asyncTasks; + std::vector> _asyncTasksBusy; /** * Database logs system */ @@ -943,10 +940,10 @@ class World static volatile bool m_stopEvent; static uint8 m_ExitCode; - uint32 m_ShutdownTimer; - uint32 m_ShutdownMask; + uint32 m_ShutdownTimer = 0; + uint32 m_ShutdownMask = 0; - uint32 m_MaintenanceTimeChecker; + uint32 m_MaintenanceTimeChecker = 0; time_t m_startTime; time_t m_gameTime; @@ -959,8 +956,8 @@ class World std::map m_accountsLastLogout; bool CanSkipQueue(WorldSession const* session); - uint32 m_maxActiveSessionCount; - uint32 m_maxQueuedSessionCount; + uint32 m_maxActiveSessionCount = 0; + uint32 m_maxQueuedSessionCount = 0; uint32 m_configUint32Values[CONFIG_UINT32_VALUE_COUNT]; int32 m_configInt32Values[CONFIG_INT32_VALUE_COUNT]; @@ -971,7 +968,7 @@ class World uint8 m_wowPatch; LocaleConstant m_defaultDbcLocale; // from config for one from loaded DBC locales - uint32 m_availableDbcLocaleMask; // by loaded DBC + uint32 m_availableDbcLocaleMask = 0; // by loaded DBC void DetectDBCLang(); bool m_allowMovement; std::string m_motd; @@ -992,18 +989,18 @@ class World static uint32 m_relocation_ai_notify_delay; // CLI command holder to be thread safe - ACE_Based::LockedQueue cliCmdQueue; + LockedQueue cliCmdQueue; //Player Queue Queue m_QueuedSessions; //sessions that are added async void AddSession_(WorldSession* s); - ACE_Based::LockedQueue addSessQueue; + LockedQueue addSessQueue; //used versions - uint32 m_anticrashRearmTimer; - ACE_Based::Thread* m_charDbWorkerThread; + uint32 m_anticrashRearmTimer = 0; + std::unique_ptr m_charDbWorkerThread; typedef std::unordered_map LogMessagesMap; LogMessagesMap m_logMessages; @@ -1011,6 +1008,8 @@ class World // Packet broadcaster std::unique_ptr m_broadcaster; + std::unique_ptr m_updateThreads; + static uint32 m_currentMSTime; static TimePoint m_currentTime; static uint32 m_currentDiff; diff --git a/src/game/WorldSession.h b/src/game/WorldSession.h index 4c70ea702..e545c1038 100644 --- a/src/game/WorldSession.h +++ b/src/game/WorldSession.h @@ -911,7 +911,7 @@ class WorldSession uint32 m_latency; uint32 m_Tutorials[ACCOUNT_TUTORIALS_COUNT]; TutorialDataState m_tutorialState; - ACE_Based::LockedQueue _recvQueue[PACKET_PROCESS_MAX_TYPE]; + LockedQueue _recvQueue[PACKET_PROCESS_MAX_TYPE]; bool _receivedPacketType[PACKET_PROCESS_MAX_TYPE]; Warden* m_warden; diff --git a/src/game/vmap/GameObjectModel.cpp b/src/game/vmap/GameObjectModel.cpp index 6f19f23c3..c75f9201b 100644 --- a/src/game/vmap/GameObjectModel.cpp +++ b/src/game/vmap/GameObjectModel.cpp @@ -69,8 +69,6 @@ void LoadGameObjectModelList() GameObjectModel::~GameObjectModel() { - if (iModel) - ((VMAP::VMapManager2*)VMAP::VMapFactory::createOrGetVMapManager())->releaseModelInstance(name); } bool GameObjectModel::initialize(GameObject const* const pGo, GameObjectDisplayInfoEntry const* pDisplayInfo) diff --git a/src/game/vmap/GameObjectModel.h b/src/game/vmap/GameObjectModel.h index 72d951dae..6cda275da 100644 --- a/src/game/vmap/GameObjectModel.h +++ b/src/game/vmap/GameObjectModel.h @@ -43,7 +43,7 @@ class GameObjectModel //G3D::Vector3 iRot; float iInvScale; float iScale; - VMAP::WorldModel* iModel; + std::shared_ptr iModel; GameObjectModel() : collision_enabled(false), iInvScale(0), iScale(0), iModel(nullptr) {} bool initialize(GameObject const* const pGo, GameObjectDisplayInfoEntry const* pDisplayInfo); diff --git a/src/game/vmap/IVMapManager.h b/src/game/vmap/IVMapManager.h index a3ea88a97..e37a127a9 100644 --- a/src/game/vmap/IVMapManager.h +++ b/src/game/vmap/IVMapManager.h @@ -48,10 +48,10 @@ namespace VMAP private: bool iEnableLineOfSightCalc; bool iEnableHeightCalc; - bool iDisableModelUnloads; + bool m_useManagedPtrs; public: - IVMapManager() : iEnableLineOfSightCalc(true), iEnableHeightCalc(true), iDisableModelUnloads(false) {} + IVMapManager() : iEnableLineOfSightCalc(true), iEnableHeightCalc(true), m_useManagedPtrs(true) {} virtual ~IVMapManager(void) {} @@ -89,12 +89,10 @@ namespace VMAP Enable/disable model unloading It is disabled by default. If it is enabled the manager will no longer process unload requests on reference clear */ - void setDisableModelUnload(bool pVal) { iDisableModelUnloads = pVal; } bool isLineOfSightCalcEnabled() const { return iEnableLineOfSightCalc; } bool isHeightCalcEnabled() const { return iEnableHeightCalc; } bool isMapLoadingEnabled() const { return iEnableLineOfSightCalc || iEnableHeightCalc; } - bool isModelUnloadDisabled() const { return iDisableModelUnloads; } virtual std::string getDirFileName(unsigned int pMapId, int x, int y) const = 0; /** @@ -104,6 +102,13 @@ namespace VMAP virtual bool getAreaInfo(unsigned int pMapId, float x, float y, float& z, uint32& flags, int32& adtId, int32& rootId, int32& groupId) const = 0; virtual bool isUnderModel(unsigned int pMapId, float x, float y, float z, float* outDist = nullptr, float* inDist = nullptr) const = 0; virtual bool GetLiquidLevel(uint32 pMapId, float x, float y, float z, uint8 ReqLiquidType, float& level, float& floor, uint32& type) const = 0; + bool getUseManagedPtrs() const { return m_useManagedPtrs; } + void setUseManagedPtrs(bool managedPtrs) { m_useManagedPtrs = managedPtrs; } }; + + + + + } #endif diff --git a/src/game/vmap/MapTree.cpp b/src/game/vmap/MapTree.cpp index 173a3fb36..aa2e2323d 100644 --- a/src/game/vmap/MapTree.cpp +++ b/src/game/vmap/MapTree.cpp @@ -358,7 +358,7 @@ bool StaticMapTree::InitMap(std::string const& fname, VMapManager2* vm) #endif if (!iIsTiled && ModelSpawn::readFromFile(rf, spawn)) { - WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name); + std::shared_ptr model = vm->acquireModelInstance(iBasePath, spawn.name); //DEBUG_FILTER_LOG(LOG_FILTER_MAP_LOADING, "StaticMapTree::InitMap(): loading %s", spawn.name.c_str()); if (model) { @@ -382,12 +382,6 @@ bool StaticMapTree::InitMap(std::string const& fname, VMapManager2* vm) void StaticMapTree::UnloadMap(VMapManager2* vm) { - for (auto& iLoadedSpawn : iLoadedSpawns) - { - iTreeValues[iLoadedSpawn.first].setUnloaded(); - for (uint32 refCount = 0; refCount < iLoadedSpawn.second; ++refCount) - vm->releaseModelInstance(iTreeValues[iLoadedSpawn.first].name); - } iLoadedSpawns.clear(); iLoadedTiles.clear(); } @@ -428,8 +422,8 @@ bool StaticMapTree::LoadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm) if (result) { // acquire model instance - WorldModel* model = vm->acquireModelInstance(iBasePath, spawn.name); - if (!model) + std::shared_ptr model = vm->acquireModelInstance(iBasePath, spawn.name); + if (model == nullptr) ERROR_LOG("StaticMapTree::LoadMapTile() could not acquire WorldModel pointer for '%s'!", spawn.name.c_str()); // update tree @@ -498,7 +492,7 @@ void StaticMapTree::UnloadMapTile(uint32 tileX, uint32 tileY, VMapManager2* vm) if (result) { // release model instance - vm->releaseModelInstance(spawn.name); + //vm->releaseModelInstance(spawn.name); // update tree uint32 referencedNode; diff --git a/src/game/vmap/ModelInstance.cpp b/src/game/vmap/ModelInstance.cpp index 6c75c3dc2..cf14d9dae 100644 --- a/src/game/vmap/ModelInstance.cpp +++ b/src/game/vmap/ModelInstance.cpp @@ -26,7 +26,7 @@ using G3D::Ray; namespace VMAP { -ModelInstance::ModelInstance(ModelSpawn const& spawn, WorldModel* model): ModelSpawn(spawn), iModel(model) +ModelInstance::ModelInstance(ModelSpawn const& spawn, std::shared_ptr model): ModelSpawn(spawn), iModel(model) { iInvRot = G3D::Matrix3::fromEulerAnglesZYX(G3D::pi() * iRot.y / 180.f, G3D::pi() * iRot.x / 180.f, G3D::pi() * iRot.z / 180.f).inverse(); iInvScale = 1.f / iScale; diff --git a/src/game/vmap/ModelInstance.h b/src/game/vmap/ModelInstance.h index bf3942b50..f077f5dfb 100644 --- a/src/game/vmap/ModelInstance.h +++ b/src/game/vmap/ModelInstance.h @@ -25,6 +25,7 @@ #include #include "Platform/Define.h" +#include namespace VMAP { @@ -66,7 +67,7 @@ namespace VMAP { public: ModelInstance(): iInvScale(0), iModel(nullptr) {} - ModelInstance(ModelSpawn const& spawn, WorldModel* model); + ModelInstance(ModelSpawn const& spawn, std::shared_ptr model); void setUnloaded() { iModel = nullptr; } bool intersectRay(G3D::Ray const& pRay, float& pMaxDist, bool pStopAtFirstHit) const; void intersectPoint(G3D::Vector3 const& p, AreaInfo& info) const; @@ -76,10 +77,11 @@ namespace VMAP protected: G3D::Matrix3 iInvRot; float iInvScale; - WorldModel* iModel; + std::shared_ptr iModel; public: - WorldModel* getWorldModel() const { return iModel; } + std::shared_ptr getWorldModel() const { return iModel; } + float getScale() const { return iInvScale; } G3D::Matrix3 const& getRot() const { return iInvRot; } }; diff --git a/src/game/vmap/VMapManager2.cpp b/src/game/vmap/VMapManager2.cpp index efa086239..e1cd64661 100644 --- a/src/game/vmap/VMapManager2.cpp +++ b/src/game/vmap/VMapManager2.cpp @@ -42,8 +42,7 @@ VMapManager2::~VMapManager2(void) { for (auto& iInstanceMapTree : iInstanceMapTrees) delete iInstanceMapTree.second; - for (auto& iLoadedModelFile : iLoadedModelFiles) - delete iLoadedModelFile.second.getModel(); + iLoadedModelFiles.clear(); } //========================================================= @@ -268,20 +267,20 @@ bool VMapManager2::GetLiquidLevel(uint32 pMapId, float x, float y, float z, uint //========================================================= -WorldModel* VMapManager2::acquireModelInstance(std::string const& basepath, std::string const& filename) +std::shared_ptr VMapManager2::acquireModelInstance(std::string const& basepath, std::string const& filename) { - m_modelsLock.acquire_read(); + std::shared_lock slock (m_modelsLock); ModelFileMap::iterator model = iLoadedModelFiles.find(filename); + std::shared_ptr ret; if (model == iLoadedModelFiles.end()) { - m_modelsLock.release(); - m_modelsLock.acquire_write(); + slock.unlock(); + std::unique_lock ulock (m_modelsLock); model = iLoadedModelFiles.find(filename); if (model != iLoadedModelFiles.end()) { - model->second.incRefCount(); - m_modelsLock.release(); - return model->second.getModel(); + ret = model->second.lock(); + return ret; } WorldModel* worldmodel = new WorldModel(); @@ -289,53 +288,37 @@ WorldModel* VMapManager2::acquireModelInstance(std::string const& basepath, std: { ERROR_LOG("VMapManager2: could not load '%s%s.vmo'!", basepath.c_str(), filename.c_str()); delete worldmodel; - m_modelsLock.release(); return nullptr; } //DEBUG_FILTER_LOG(LOG_FILTER_MAP_LOADING, "VMapManager2: loading file '%s%s'.", basepath.c_str(), filename.c_str()); - model = iLoadedModelFiles.insert(std::pair(filename, ManagedModel())).first; - model->second.setModel(worldmodel); + ret = std::shared_ptr( + worldmodel, + [this, filename](WorldModel*){ + std::unique_lock lock(m_modelsLock); + iLoadedModelFiles.erase(filename); + }); + model = iLoadedModelFiles.insert(std::pair( + filename, + {ret, getUseManagedPtrs()} + )).first; + return ret; } - model->second.incRefCount(); - m_modelsLock.release(); - return model->second.getModel(); + ret = model->second.lock(); + return ret; } -void VMapManager2::releaseModelInstance(std::string const& filename) -{ - m_modelsLock.acquire_read(); - ModelFileMap::iterator model = iLoadedModelFiles.find(filename); - if (model == iLoadedModelFiles.end()) - { - ERROR_LOG("VMapManager2: trying to unload non-loaded file '%s'!", filename.c_str()); - m_modelsLock.release(); - return; - } - int decreasedValue = model->second.decRefCount(); - if (!isModelUnloadDisabled() && decreasedValue <= 0) - { - m_modelsLock.release(); - m_modelsLock.acquire_write(); - model = iLoadedModelFiles.find(filename); - if (model == iLoadedModelFiles.end()) // Deleted in another thread - { - m_modelsLock.release(); - return; - } - - if (model->second.getRefCount() <= 0) - { - //DEBUG_FILTER_LOG(LOG_FILTER_MAP_LOADING, "VMapManager2: unloading file '%s'", filename.c_str()); - delete model->second.getModel(); - iLoadedModelFiles.erase(model); - } - } - m_modelsLock.release(); -} //========================================================= bool VMapManager2::existsMap(char const* pBasePath, unsigned int pMapId, int x, int y) { return StaticMapTree::CanLoadMap(std::string(pBasePath), pMapId, x, y); } + +ManagedModel::ManagedModel(const std::shared_ptr &ptr, bool managed) : + std::weak_ptr(ptr) +{ + if (managed) + m_persistent = lock(); +} + } // namespace VMAP diff --git a/src/game/vmap/VMapManager2.h b/src/game/vmap/VMapManager2.h index f351a7039..f0b598e43 100644 --- a/src/game/vmap/VMapManager2.h +++ b/src/game/vmap/VMapManager2.h @@ -23,8 +23,9 @@ #include #include "Platform/Define.h" #include -#include -#include +#include +#include +#include //=========================================================== @@ -48,18 +49,13 @@ namespace VMAP class WorldModel; class ModelInstance; - class ManagedModel + class ManagedModel : + public std::weak_ptr { - public: - ManagedModel() : iModel(nullptr), iRefCount(0) {} - void setModel(WorldModel* model) { iModel = model; } - WorldModel* getModel() const { return iModel; } - void incRefCount() { ++iRefCount; } - int decRefCount() { return --iRefCount; } - int getRefCount() const { return iRefCount.value(); } - protected: - WorldModel* iModel; - ACE_Atomic_Op iRefCount; + public: + ManagedModel(const std::shared_ptr &ptr, bool managed); + private: + std::shared_ptr m_persistent; }; typedef std::unordered_map InstanceTreeMap; @@ -75,7 +71,7 @@ namespace VMAP bool _loadMap(uint32 pMapId, std::string const& basePath, uint32 tileX, uint32 tileY); /* void _unloadMap(uint32 pMapId, uint32 x, uint32 y); */ - ACE_RW_Mutex m_modelsLock; + std::shared_timed_mutex m_modelsLock; public: // public for debug G3D::Vector3 convertPositionToInternalRep(float x, float y, float z) const; @@ -103,8 +99,7 @@ namespace VMAP bool isUnderModel(unsigned int pMapId, float x, float y, float z, float* outDist = nullptr, float* inDist = nullptr) const override; bool GetLiquidLevel(uint32 pMapId, float x, float y, float z, uint8 ReqLiquidType, float& level, float& floor, uint32& type) const override; - WorldModel* acquireModelInstance(std::string const& basepath, std::string const& filename); - void releaseModelInstance(std::string const& filename); + std::shared_ptr acquireModelInstance(std::string const& basepath, std::string const& filename); // what's the use of this? o.O std::string getDirFileName(unsigned int pMapId, int /*x*/, int /*y*/) const override diff --git a/src/mangosd/CMakeLists.txt b/src/mangosd/CMakeLists.txt index 5d07332fb..b9a08beda 100644 --- a/src/mangosd/CMakeLists.txt +++ b/src/mangosd/CMakeLists.txt @@ -16,24 +16,24 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA set(EXECUTABLE_NAME mangosd) -set (EXECUTABLE_SRCS - ChatSocket.h - CliRunnable.h - MaNGOSsoap.h - Master.h - RASocket.h - soapH.h - soapStub.h - WorldRunnable.h - ChatSocket.cpp - CliRunnable.cpp - Main.cpp - MaNGOSsoap.cpp - Master.cpp - RASocket.cpp - soapC.cpp - soapServer.cpp - WorldRunnable.cpp +set(EXECUTABLE_SRCS + ChatSocket.h + CliRunnable.h + MaNGOSsoap.h + Master.h + RASocket.h + soapH.h + soapStub.h + WorldRunnable.h + ChatSocket.cpp + CliRunnable.cpp + Main.cpp + MaNGOSsoap.cpp + Master.cpp + RASocket.cpp + soapC.cpp + soapServer.cpp + WorldRunnable.cpp ) diff --git a/src/mangosd/ChatSocket.cpp b/src/mangosd/ChatSocket.cpp index 2181a677d..6d5205859 100644 --- a/src/mangosd/ChatSocket.cpp +++ b/src/mangosd/ChatSocket.cpp @@ -106,7 +106,7 @@ int OfflineChatSocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask) { if(closing_) return -1; - ACE_GUARD_RETURN (ACE_Thread_Mutex, Guard, outBufferLock, -1); + std::unique_lock lock (outBufferLock); closing_ = true; @@ -118,7 +118,7 @@ int OfflineChatSocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask) int OfflineChatSocket::handle_output (ACE_HANDLE) { - ACE_GUARD_RETURN (ACE_Thread_Mutex, Guard, outBufferLock, -1); + std::unique_lock lock (outBufferLock); if(closing_) return -1; @@ -334,7 +334,7 @@ int OfflineChatSocket::handle_input(ACE_HANDLE) /// Output function int OfflineChatSocket::sendf(const char* msg) { - ACE_GUARD_RETURN (ACE_Thread_Mutex, Guard, outBufferLock, -1); + std::unique_lock lock (outBufferLock); if (closing_) return -1; diff --git a/src/mangosd/ChatSocket.h b/src/mangosd/ChatSocket.h index cfe9b24c0..2c11417ec 100644 --- a/src/mangosd/ChatSocket.h +++ b/src/mangosd/ChatSocket.h @@ -31,7 +31,6 @@ #include #include #include -#include #include #define OFFCHAT_BUFF_SIZE 8192 @@ -80,7 +79,7 @@ class OfflineChatSocket: protected OfflineChatHandler char inputBuffer[OFFCHAT_BUFF_SIZE]; uint32 inputBufferLen; - ACE_Thread_Mutex outBufferLock; + std::mutex outBufferLock; char outputBuffer[OFFCHAT_BUFF_SIZE]; uint32 outputBufferLen; diff --git a/src/mangosd/CliRunnable.cpp b/src/mangosd/CliRunnable.cpp index 0f330064d..269b26971 100644 --- a/src/mangosd/CliRunnable.cpp +++ b/src/mangosd/CliRunnable.cpp @@ -81,7 +81,7 @@ int kb_hit_return() #endif /// %Thread start -void CliRunnable::run() +void CliRunnable::operator()() { ///- Init new SQL thread for the world database (one connection call enough) WorldDatabase.ThreadStart(); // let thread do safe mySQL requests @@ -109,6 +109,30 @@ void CliRunnable::run() if (World::IsStopped()) break; #endif + +#ifndef WIN32 + + int retval; + do + { + fd_set rfds; + struct timeval tv; + tv.tv_sec = 1; + tv.tv_usec = 0; + + FD_ZERO(&rfds); + FD_SET(0, &rfds); + + retval = select(1, &rfds, nullptr, nullptr, &tv); + } while (!retval); + + if (retval == -1) + { + World::StopNow(SHUTDOWN_EXIT_CODE); + break; + } +#endif + char *command_str = fgets(commandbuf,sizeof(commandbuf),stdin); if (command_str != nullptr) { diff --git a/src/mangosd/CliRunnable.h b/src/mangosd/CliRunnable.h index db311db0b..bc83aa45e 100644 --- a/src/mangosd/CliRunnable.h +++ b/src/mangosd/CliRunnable.h @@ -27,13 +27,12 @@ #define __CLIRUNNABLE_H #include "Common.h" -#include "Threading.h" /// Command Line Interface handling thread -class CliRunnable : public ACE_Based::Runnable +class CliRunnable { - public: - void run(); +public: + void operator()(); }; #endif /// @} diff --git a/src/mangosd/MaNGOSsoap.h b/src/mangosd/MaNGOSsoap.h index e26905db7..a1db7d8c9 100644 --- a/src/mangosd/MaNGOSsoap.h +++ b/src/mangosd/MaNGOSsoap.h @@ -34,10 +34,9 @@ #include -class MaNGOSsoapRunnable: public ACE_Based::Runnable +class MaNGOSsoapRunnable { public: - MaNGOSsoapRunnable() { } void run(); void setListenArguments(std::string host, uint16 port) { diff --git a/src/mangosd/Master.cpp b/src/mangosd/Master.cpp index 392cf5578..7ae9c2d34 100644 --- a/src/mangosd/Master.cpp +++ b/src/mangosd/Master.cpp @@ -64,187 +64,136 @@ INSTANTIATE_SINGLETON_1( Master ); volatile uint32 Master::m_masterLoopCounter = 0; volatile bool Master::m_handleSigvSignals = false; -class FreezeDetectorRunnable : public ACE_Based::Runnable +void freezeDetector(uint32 _delaytime) { -public: - FreezeDetectorRunnable() { _delaytime = 0; } - uint32 m_loops, m_lastchange; - uint32 w_loops, w_lastchange; - uint32 _delaytime; - void SetDelayTime(uint32 t) { _delaytime = t; } - void run(void) + if(!_delaytime) + return; + sLog.outString("Starting up anti-freeze thread (%u seconds max stuck time)...",_delaytime/1000); + uint32 loops = 0; + uint32 lastchange = 0; + while(!World::IsStopped()) { - if(!_delaytime) - return; - sLog.outString("Starting up anti-freeze thread (%u seconds max stuck time)...",_delaytime/1000); - m_loops = 0; - w_loops = 0; - m_lastchange = 0; - w_lastchange = 0; - while(!World::IsStopped()) + std::this_thread::sleep_for(std::chrono::seconds(1)); + + uint32 curtime = WorldTimer::getMSTime(); + //DEBUG_LOG("anti-freeze: time=%u, counters=[%u; %u]",curtime,Master::m_masterLoopCounter,World::m_worldLoopCounter); + + // normal work + if (loops != World::m_worldLoopCounter) { - ACE_Based::Thread::Sleep(1000); - - uint32 curtime = WorldTimer::getMSTime(); - //DEBUG_LOG("anti-freeze: time=%u, counters=[%u; %u]",curtime,Master::m_masterLoopCounter,World::m_worldLoopCounter); - - // normal work - if (w_loops != World::m_worldLoopCounter) - { - w_lastchange = curtime; - w_loops = World::m_worldLoopCounter; - } - // possible freeze + lastchange = curtime; + loops = World::m_worldLoopCounter; + } + // possible freeze #ifdef NDEBUG - else if (WorldTimer::getMSTimeDiff(w_lastchange, curtime) > _delaytime) - { - sLog.outError("World Thread hangs, kicking out server!"); - signal(SIGSEGV, 0); - Master::m_handleSigvSignals = false; // disable anticrash - *((uint32 volatile*)nullptr) = 0; // bang crash - } + else if (WorldTimer::getMSTimeDiff(lastchange, curtime) > _delaytime) + { + sLog.outError("World Thread hangs, kicking out server!"); + std::terminate(); // bang crash + } #endif - } - // Fix crash au shutdown du serv. sLog n'existe plus ici. - //sLog.outString("Anti-freeze thread exiting without problems."); } -}; + // Fix crash au shutdown du serv. sLog n'existe plus ici. + //sLog.outString("Anti-freeze thread exiting without problems."); +} -class RARunnable : public ACE_Based::Runnable +void remoteAccess() { -private: - ACE_Reactor *m_Reactor; - RASocket::Acceptor *m_Acceptor; -public: - RARunnable() + #if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) + + ACE_Dev_Poll_Reactor imp; + + imp.max_notify_iterations (128); + imp.restart (1); + + #else + + ACE_TP_Reactor imp; + imp.max_notify_iterations (128); + + #endif + + ACE_Reactor reactor(&imp, 1 /* 1= delete implementation so we don't have to care */); + + RASocket::Acceptor acceptor; + + uint16 raport = sConfig.GetIntDefault ("Ra.Port", 3443); + std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0"); + + ACE_INET_Addr listen_addr(raport, stringip.c_str()); + + if (acceptor.open (listen_addr, &reactor, ACE_NONBLOCK) == -1) { - ACE_Reactor_Impl* imp = 0; - - #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); - - #else - - imp = new ACE_TP_Reactor (); - imp->max_notify_iterations (128); - - #endif - - m_Reactor = new ACE_Reactor (imp, 1 /* 1= delete implementation so we don't have to care */); - - m_Acceptor = new RASocket::Acceptor; - + sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ()); } - ~RARunnable() + sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ()); + + while (!reactor.reactor_event_loop_done()) { - delete m_Reactor; - delete m_Acceptor; - } + ACE_Time_Value interval (0, 10000); - void run () - { - uint16 raport = sConfig.GetIntDefault ("Ra.Port", 3443); - std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0"); + if (reactor.run_reactor_event_loop (interval) == -1) + break; - ACE_INET_Addr listen_addr(raport, stringip.c_str()); - - if (m_Acceptor->open (listen_addr, m_Reactor, ACE_NONBLOCK) == -1) + if(World::IsStopped()) { - sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ()); + acceptor.close(); + break; } - - sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ()); - - while (!m_Reactor->reactor_event_loop_done()) - { - ACE_Time_Value interval (0, 10000); - - if (m_Reactor->run_reactor_event_loop (interval) == -1) - break; - - if(World::IsStopped()) - { - m_Acceptor->close(); - break; - } - } - sLog.outString("RARunnable thread ended"); } -}; + sLog.outString("RARunnable thread ended"); +} -class OfflineChatRunnable : public ACE_Based::Runnable +void offlineChat() { -private: - ACE_Reactor *m_Reactor; - OfflineChatSocket::Acceptor *m_Acceptor; -public: - OfflineChatRunnable() +#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) + + ACE_Dev_Poll_Reactor imp; + + imp.max_notify_iterations(128); + imp.restart(1); + +#else + + ACE_TP_Reactor imp; + imp.max_notify_iterations(128); + +#endif + + ACE_Reactor m_Reactor(&imp); + + OfflineChatSocket::Acceptor m_Acceptor; + + LoginDatabase.ThreadStart(); + uint16 raport = sConfig.GetIntDefault ("OfflineChat.Port", 3444); + std::string stringip = sConfig.GetStringDefault ("OfflineChat.IP", "0.0.0.0"); + + ACE_INET_Addr listen_addr(raport, stringip.c_str()); + + if (m_Acceptor.open (listen_addr, &m_Reactor, ACE_NONBLOCK) == -1) { - ACE_Reactor_Impl* imp = 0; - - #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); - - #else - - imp = new ACE_TP_Reactor (); - imp->max_notify_iterations (128); - - #endif - - m_Reactor = new ACE_Reactor (imp, 1 /* 1= delete implementation so we don't have to care */); - - m_Acceptor = new OfflineChatSocket::Acceptor; - + sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ()); } - ~OfflineChatRunnable() + sLog.outString ("Starting offline-chat listener on port %d on %s", raport, stringip.c_str ()); + + while (!m_Reactor.reactor_event_loop_done()) { - delete m_Reactor; - delete m_Acceptor; - } + ACE_Time_Value interval (0, 10000); - void run () - { - LoginDatabase.ThreadStart(); - uint16 raport = sConfig.GetIntDefault ("OfflineChat.Port", 3444); - std::string stringip = sConfig.GetStringDefault ("OfflineChat.IP", "0.0.0.0"); + if (m_Reactor.run_reactor_event_loop (interval) == -1) + break; - ACE_INET_Addr listen_addr(raport, stringip.c_str()); - - if (m_Acceptor->open (listen_addr, m_Reactor, ACE_NONBLOCK) == -1) + if (World::IsStopped()) { - sLog.outError ("MaNGOS RA can not bind to port %d on %s", raport, stringip.c_str ()); + m_Acceptor.close(); + break; } - - sLog.outString ("Starting offline-chat listener on port %d on %s", raport, stringip.c_str ()); - - while (!m_Reactor->reactor_event_loop_done()) - { - ACE_Time_Value interval (0, 10000); - - if (m_Reactor->run_reactor_event_loop (interval) == -1) - break; - - if (World::IsStopped()) - { - m_Acceptor->close(); - break; - } - } - LoginDatabase.ThreadEnd(); - sLog.outString("OfflineChatRunnable thread ended"); } -}; + LoginDatabase.ThreadEnd(); + sLog.outString("OfflineChatRunnable thread ended"); +} Master::Master() { @@ -296,8 +245,8 @@ int Master::Run() _HookSignals(); ///- Launch WorldRunnable thread - ACE_Based::Thread world_thread(new WorldRunnable); - world_thread.setPriority(ACE_Based::Highest); + std::thread world_thread{WorldRunnable()}; + // world_thread.setPriority(ACE_Based::Highest); // set realmbuilds depend on mangosd expected builds, and set server online { @@ -307,7 +256,7 @@ int Master::Run() LoginDatabase.PExecute("UPDATE `realmlist` SET `realmflags` = `realmflags` & ~(%u), `population` = 0, `realmbuilds` = '%s' WHERE `id` = '%u'", REALM_FLAG_OFFLINE, builds.c_str(), realmID); } - ACE_Based::Thread* cliThread = nullptr; + std::thread* cliThread = nullptr; #ifdef WIN32 if (sConfig.GetBoolDefault("Console.Enable", true) && (m_ServiceStatus == -1)/* need disable console in service mode*/) @@ -316,15 +265,15 @@ int Master::Run() #endif { ///- Launch CliRunnable thread - cliThread = new ACE_Based::Thread(new CliRunnable); + cliThread = new std::thread(CliRunnable()); } - ACE_Based::Thread* rar_thread = nullptr; + std::thread* rar_thread = nullptr; if (sConfig.GetBoolDefault ("Ra.Enable", false)) - rar_thread = new ACE_Based::Thread(new RARunnable); - ACE_Based::Thread* offlinechat_thread = nullptr; + rar_thread = new std::thread(&remoteAccess); + std::thread* offlinechat_thread = nullptr; if (sConfig.GetBoolDefault ("OfflineChat.Enable", false)) - offlinechat_thread = new ACE_Based::Thread(new OfflineChatRunnable); + offlinechat_thread = new std::thread(&offlineChat); ///- Handle affinity for multiple processors and process priority on Windows #ifdef WIN32 @@ -370,24 +319,23 @@ int Master::Run() #endif ///- Start soap serving thread - ACE_Based::Thread* soap_thread = nullptr; + std::thread* soap_thread = nullptr; if(sConfig.GetBoolDefault("SOAP.Enabled", false)) { - MaNGOSsoapRunnable *runnable = new MaNGOSsoapRunnable(); - - runnable->setListenArguments(sConfig.GetStringDefault("SOAP.IP", "127.0.0.1"), sConfig.GetIntDefault("SOAP.Port", 7878)); - soap_thread = new ACE_Based::Thread(runnable); + soap_thread = new std::thread([](){ + MaNGOSsoapRunnable runnable; + runnable.setListenArguments(sConfig.GetStringDefault("SOAP.IP", "127.0.0.1"), sConfig.GetIntDefault("SOAP.Port", 7878)); + runnable.run(); + }); } ///- Start up freeze catcher thread - ACE_Based::Thread* freeze_thread = nullptr; + std::thread* freeze_thread = nullptr; if(uint32 freeze_delay = sConfig.GetIntDefault("MaxCoreStuckTime", 0)) { - FreezeDetectorRunnable *fdr = new FreezeDetectorRunnable(); - fdr->SetDelayTime(freeze_delay*1000); - freeze_thread = new ACE_Based::Thread(fdr); - freeze_thread->setPriority(ACE_Based::Highest); + freeze_thread = new std::thread(std::bind(&freezeDetector,freeze_delay*1000)); + //freeze_thread->setPriority(ACE_Based::Highest); } // Wait for clients ? @@ -414,15 +362,14 @@ int Master::Run() ///- Stop freeze protection before shutdown tasks if (freeze_thread) { - freeze_thread->destroy(); + freeze_thread->join(); delete freeze_thread; } ///- Stop soap thread if(soap_thread) { - soap_thread->wait(); - soap_thread->destroy(); + soap_thread->join(); delete soap_thread; } @@ -434,19 +381,17 @@ int Master::Run() // when the main thread closes the singletons get unloaded // since worldrunnable uses them, it will crash if unloaded after master - world_thread.wait(); + world_thread.join(); if(rar_thread) { - rar_thread->wait(); - rar_thread->destroy(); + rar_thread->join(); delete rar_thread; } if (offlinechat_thread) { - offlinechat_thread->wait(); - offlinechat_thread->destroy(); + offlinechat_thread->join(); delete offlinechat_thread; } @@ -469,8 +414,8 @@ int Master::Run() if (cliThread) { - #ifdef WIN32 +#ifdef WIN32 // this only way to terminate CLI thread exist at Win32 (alt. way exist only in Windows Vista API) //_exit(1); // send keyboard input to safely unblock the CLI thread @@ -505,14 +450,11 @@ int Master::Run() b[3].Event.KeyEvent.wRepeatCount = 1; DWORD numb; WriteConsoleInput(hStdIn, b, 4, &numb); - - cliThread->wait(); - - #else - - cliThread->destroy(); - - #endif +#else + fclose(stdin); +#endif + if (cliThread->joinable()) + cliThread->join(); delete cliThread; } @@ -632,7 +574,7 @@ void createdump(void) abort(); } #endif - + } /// Handle termination signals void Master::SigvSignalHandler() @@ -658,6 +600,7 @@ void Master::_OnSignal(int s) signal(SIGSEGV, 0); if (!m_handleSigvSignals) return; + std::exception_ptr exc = std::current_exception(); m_handleSigvSignals = false; // Desarm anticrash sWorld.SetAnticrashRearmTimer(sWorld.getConfig(CONFIG_UINT32_ANTICRASH_REARM_TIMER)); uint32 anticrashOptions = sWorld.getConfig(CONFIG_UINT32_ANTICRASH_OPTIONS); @@ -673,15 +616,15 @@ void Master::_OnSignal(int s) sWorld.SendWorldText(LANG_SYSTEMMESSAGE, "Server has crashed. Now saving online players ..."); else sWorld.SendWorldText(LANG_SYSTEMMESSAGE, "Crash server occurred :("); - ACE_Based::Thread::Sleep(500); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); } if (anticrashOptions & ANTICRASH_OPTION_SAVEALL) { CharacterDatabase.ThreadStart(); sObjectAccessor.SaveAllPlayers(); - ACE_Based::Thread::Sleep(25000); // Wait enough time to execute the SQL queries. + std::this_thread::sleep_for(std::chrono::seconds(25)); } - *((volatile int*)nullptr) = 42; // Crash for real now. + std::rethrow_exception(exc); // Crash for real now. return; } diff --git a/src/mangosd/RASocket.cpp b/src/mangosd/RASocket.cpp index 8218aaeec..6d3f722ae 100644 --- a/src/mangosd/RASocket.cpp +++ b/src/mangosd/RASocket.cpp @@ -103,7 +103,7 @@ int RASocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask) if(closing_) return -1; DEBUG_LOG("RASocket::handle_close"); - ACE_GUARD_RETURN (ACE_Thread_Mutex, Guard, outBufferLock, -1); + std::unique_lock lock (outBufferLock); closing_ = true; @@ -115,7 +115,7 @@ int RASocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask) int RASocket::handle_output (ACE_HANDLE) { - ACE_GUARD_RETURN (ACE_Thread_Mutex, Guard, outBufferLock, -1); + std::unique_lock lock (outBufferLock); if(closing_) return -1; @@ -301,7 +301,7 @@ void RASocket::commandFinished(void* callbackArg, bool /*sucess*/) int RASocket::sendf(const char* msg) { - ACE_GUARD_RETURN (ACE_Thread_Mutex, Guard, outBufferLock, -1); + std::unique_lock lock (outBufferLock); if(closing_) return -1; diff --git a/src/mangosd/RASocket.h b/src/mangosd/RASocket.h index 5457dcf68..34f79292b 100644 --- a/src/mangosd/RASocket.h +++ b/src/mangosd/RASocket.h @@ -31,7 +31,6 @@ #include #include #include -#include #include #define RA_BUFF_SIZE 8192 @@ -75,7 +74,7 @@ class RASocket: protected RAHandler char inputBuffer[RA_BUFF_SIZE]; uint32 inputBufferLen; - ACE_Thread_Mutex outBufferLock; + std::mutex outBufferLock; char outputBuffer[RA_BUFF_SIZE]; uint32 outputBufferLen; diff --git a/src/mangosd/WorldRunnable.cpp b/src/mangosd/WorldRunnable.cpp index 5b6cd806e..0ef2e381f 100644 --- a/src/mangosd/WorldRunnable.cpp +++ b/src/mangosd/WorldRunnable.cpp @@ -43,7 +43,7 @@ extern int m_ServiceStatus; #endif /// Heartbeat for the World -void WorldRunnable::run() +void WorldRunnable::operator()() { ///- Init new SQL thread for the world database WorldDatabase.ThreadStart(); // let thread do safe mySQL requests (one connection call enough) @@ -95,7 +95,7 @@ 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/mangosd/WorldRunnable.h b/src/mangosd/WorldRunnable.h index 500cf3ead..a69067d4e 100644 --- a/src/mangosd/WorldRunnable.h +++ b/src/mangosd/WorldRunnable.h @@ -27,13 +27,12 @@ #define __WORLDRUNNABLE_H #include "Common.h" -#include "Threading.h" /// Heartbeat thread for the World -class WorldRunnable : public ACE_Based::Runnable +class WorldRunnable { public: - void run(); + void operator()(); }; #endif /// @} diff --git a/src/realmd/CMakeLists.txt b/src/realmd/CMakeLists.txt index 4eaa48324..8bdb25a0d 100644 --- a/src/realmd/CMakeLists.txt +++ b/src/realmd/CMakeLists.txt @@ -16,17 +16,17 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA set(EXECUTABLE_NAME realmd) -set (EXECUTABLE_SRCS - AuthCodes.h - AuthSocket.h - BufferedSocket.h - PatchHandler.h - RealmList.h - AuthSocket.cpp - BufferedSocket.cpp - Main.cpp - PatchHandler.cpp - RealmList.cpp +set(EXECUTABLE_SRCS + AuthCodes.h + AuthSocket.h + BufferedSocket.h + PatchHandler.h + RealmList.h + AuthSocket.cpp + BufferedSocket.cpp + Main.cpp + PatchHandler.cpp + RealmList.cpp ) diff --git a/src/realmd/PatchHandler.cpp b/src/realmd/PatchHandler.cpp index 15eca7d67..b50550810 100644 --- a/src/realmd/PatchHandler.cpp +++ b/src/realmd/PatchHandler.cpp @@ -35,6 +35,9 @@ #include +#include "Policies/SingletonImp.h" +#include "Policies/ThreadingModel.h" + #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0 #endif @@ -145,9 +148,14 @@ PatchCache::PatchCache() LoadPatchesInfo(); } + +using PatchCacheLock = MaNGOS::ClassLevelLockable; +INSTANTIATE_SINGLETON_2(PatchCache, PatchCacheLock); +INSTANTIATE_CLASS_MUTEX(PatchCache, std::mutex); + PatchCache* PatchCache::instance() { - return ACE_Singleton::instance(); + return &MaNGOS::Singleton::Instance(); } void PatchCache::LoadPatchMD5(const char* szFileName) diff --git a/src/realmd/PatchHandler.h b/src/realmd/PatchHandler.h index 6ca5c91e5..9f3d93336 100644 --- a/src/realmd/PatchHandler.h +++ b/src/realmd/PatchHandler.h @@ -33,7 +33,6 @@ #include #include #include -#include #include #include diff --git a/src/shared/CMakeLists.txt b/src/shared/CMakeLists.txt index 14bfedc6e..21bda69a9 100644 --- a/src/shared/CMakeLists.txt +++ b/src/shared/CMakeLists.txt @@ -30,7 +30,7 @@ set (shared_SRCS revision.h ServiceWin32.h SystemConfig.h - Threading.h + ThreadPool.h Timer.h Util.h WheatyExceptionReport.h @@ -69,7 +69,7 @@ set (shared_SRCS PosixDaemon.cpp ProgressBar.cpp ServiceWin32.cpp - Threading.cpp + ThreadPool.cpp Util.cpp Duration.h WheatyExceptionReport.cpp diff --git a/src/shared/Common.h b/src/shared/Common.h index eeed8749c..154a8609d 100644 --- a/src/shared/Common.h +++ b/src/shared/Common.h @@ -92,12 +92,9 @@ typedef std::chrono::time_point #include -#include -#include #include // Old ACE versions (pre-ACE-5.5.4) not have this type (add for allow use at Unix side external old ACE versions) diff --git a/src/shared/Config/Config.cpp b/src/shared/Config/Config.cpp index 37aa728f5..0381d33d9 100644 --- a/src/shared/Config/Config.cpp +++ b/src/shared/Config/Config.cpp @@ -23,7 +23,8 @@ #include "Policies/SingletonImp.h" -INSTANTIATE_SINGLETON_1(Config); +INSTANTIATE_SINGLETON_2(Config, Config::Lock); +INSTANTIATE_CLASS_MUTEX(Config, std::shared_timed_mutex); // Defined here as it must not be exposed to end-users. bool Config::GetValueHelper(char const* name, ACE_TString& result) diff --git a/src/shared/Config/Config.h b/src/shared/Config/Config.h index 3b399d21a..88b3dae06 100644 --- a/src/shared/Config/Config.h +++ b/src/shared/Config/Config.h @@ -23,17 +23,18 @@ #define CONFIG_H #include "Common.h" -#include -#include #include "Platform/Define.h" #include "ace/Configuration_Import_Export.h" +#include "Policies/SingletonImp.h" +#include "Policies/ThreadingModel.h" +#include class ACE_Configuration_Heap; class Config { - friend class ACE_Singleton; public: + using Lock = MaNGOS::ClassLevelLockable; Config(); ~Config(); @@ -50,18 +51,19 @@ class Config bool GetValueHelper(char const* name, ACE_TString &result); private: + friend class MaNGOS::Singleton; std::string mFilename; ACE_Configuration_Heap* mConf; - typedef ACE_Thread_Mutex LockType; - typedef ACE_Guard GuardType; + using LockType = std::mutex; + using GuardType = std::unique_lock; std::string _filename; LockType m_configLock; }; // Nostalrius : multithreading lock -#define sConfig (*ACE_Singleton::instance()) +#define sConfig (MaNGOS::Singleton::Instance()) #endif diff --git a/src/shared/Database/Database.cpp b/src/shared/Database/Database.cpp index 10fd696b2..217c71f8f 100644 --- a/src/shared/Database/Database.cpp +++ b/src/shared/Database/Database.cpp @@ -184,11 +184,9 @@ bool Database::Initialize(char const* infoString, int nConns /*= 1*/, int nWorke return false; m_numAsyncWorkers = nWorkers; - m_threadsBodies = new SqlDelayThread*[m_numAsyncWorkers]; - m_delayThreads = new ACE_Based::Thread*[m_numAsyncWorkers]; - m_serialDelayQueue = new SqlQueue*[m_numAsyncWorkers]; + for (int i = 0; i < nWorkers; ++i) - if (!InitDelayThread(i, infoString)) + if (!InitDelayThread(infoString)) return false; return true; @@ -220,40 +218,37 @@ void Database::StopServer() } -bool Database::InitDelayThread(int i, std::string const& infoString) +bool Database::InitDelayThread(std::string const& infoString) { //New delay thread for delay execute SqlConnection* threadConnection = CreateConnection(); if(!threadConnection->Initialize(infoString.c_str())) return false; - m_threadsBodies[i] = new SqlDelayThread(this, threadConnection, i); - m_threadsBodies[i]->incReference(); - m_delayThreads[i] = new ACE_Based::Thread(m_threadsBodies[i]); - m_serialDelayQueue[i] = new SqlQueue(); + std::shared_ptr tbody = std::make_shared(this, threadConnection); + m_threadsBodies.emplace_back(tbody); + m_delayThreads.emplace_back([tbody](){ + tbody->run(); + }); return true; } void Database::HaltDelayThread() { - if (!m_delayThreads || !m_threadsBodies) + if (m_delayThreads.empty() || m_threadsBodies.empty()) return; for (uint32 i = 0; i < m_numAsyncWorkers; ++i) - { m_threadsBodies[i]->Stop(); - m_delayThreads[i]->wait(); - delete m_delayThreads[i]; - m_threadsBodies[i]->decReference(); - } - delete[] m_threadsBodies; - delete[] m_delayThreads; - delete[] m_serialDelayQueue; - m_delayThreads = nullptr; - m_threadsBodies = nullptr; - m_serialDelayQueue = nullptr; + + for (uint32 i = 0; i < m_numAsyncWorkers; ++i) + m_delayThreads[i].join(); + + m_threadsBodies.clear(); + m_delayThreads.clear(); + m_numAsyncWorkers = 0; } @@ -551,23 +546,15 @@ void Database::AddToSerialDelayQueue(SqlOperation* op) // TODO: Load balance, must maintain mapping of serial ID so queries are // executed sequentially, however int worker = op->GetSerialId() % m_numAsyncWorkers; - m_serialDelayQueue[worker]->add(op); -} - -bool Database::NextSerialDelayedOperation(int workerId, SqlOperation*& op) -{ - if (workerId >= m_numAsyncWorkers) - return false; - - return m_serialDelayQueue[workerId]->next(op); + m_threadsBodies[worker]->addSerialOperation(op); } bool Database::HasAsyncQuery() { bool hasQuery = !m_delayQueue->empty_unsafe(); - for (int i = 0; i < m_numAsyncWorkers && m_serialDelayQueue && !hasQuery; ++i) - hasQuery = !m_serialDelayQueue[i]->empty_unsafe(); + for (int i = 0; i < m_numAsyncWorkers && !hasQuery; ++i) + hasQuery = m_threadsBodies[i]->HasAsyncQuery(); return hasQuery; } diff --git a/src/shared/Database/Database.h b/src/shared/Database/Database.h index f916d237c..ed46644cb 100644 --- a/src/shared/Database/Database.h +++ b/src/shared/Database/Database.h @@ -22,14 +22,14 @@ #ifndef DATABASE_H #define DATABASE_H -#include "Threading.h" #include #include "Database/SqlDelayThread.h" -#include #include "Policies/ThreadingModel.h" #include -#include #include "SqlPreparedStatement.h" +#include +#include +#include class SqlTransaction; class SqlResultQueue; @@ -40,7 +40,7 @@ class Database; #define MAX_QUERY_LEN (32*1024) -typedef ACE_Based::LockedQueue SqlQueue; +using SqlQueue = LockedQueue; // class SqlConnection @@ -75,13 +75,13 @@ class SqlConnection class Lock { public: - Lock(SqlConnection* conn) : m_pConn(conn) { m_pConn->m_mutex.acquire(); } - ~Lock() { m_pConn->m_mutex.release(); } + Lock(SqlConnection * conn) : m_pConn(conn) {} SqlConnection* operator->() const { return m_pConn; } private: - SqlConnection* const m_pConn; + SqlConnection * const m_pConn; + std::unique_lock m_lock{m_pConn->m_mutex}; }; //get DB object @@ -108,7 +108,7 @@ class SqlConnection std::string m_database; private: - typedef ACE_Recursive_Thread_Mutex LOCK_TYPE; + using LOCK_TYPE = std::recursive_mutex; LOCK_TYPE m_mutex; typedef std::vector StmtHolder; @@ -122,7 +122,7 @@ class Database virtual bool Initialize(char const* infoString, int nConns = 1, int nWorkers = 1); //start worker thread for async DB request execution - virtual bool InitDelayThread(int i, std::string const& infoString); + virtual bool InitDelayThread(std::string const& infoString); //stop worker thread virtual void HaltDelayThread(); @@ -264,7 +264,7 @@ class Database inline void AddToDelayQueue(SqlOperation* op) { m_delayQueue->add(op); } inline bool NextDelayedOperation(SqlOperation*& op) { return m_delayQueue->next(op); } - inline void AddToSerialDelayQueue(int workerId, SqlOperation* op) { m_serialDelayQueue[workerId]->add(op); } + inline void AddToSerialDelayQueue(int workerId, SqlOperation* op) { m_threadsBodies[workerId]->addSerialOperation(op); } bool NextSerialDelayedOperation(int workerId, SqlOperation*& op); bool HasAsyncQuery(); @@ -274,8 +274,8 @@ class Database // Frees data, cancels scheduled queries, closes connection void StopServer(); protected: - Database() : m_nQueryConnPoolSize(1), m_delayQueue(new SqlQueue()), m_serialDelayQueue(nullptr), m_pAsyncConn(nullptr), - m_pResultQueue(nullptr), m_numAsyncWorkers(0), m_threadsBodies(nullptr), m_delayThreads(nullptr), + Database() : m_nQueryConnPoolSize(1), m_delayQueue(new SqlQueue()), m_pAsyncConn(nullptr), + m_pResultQueue(nullptr), m_numAsyncWorkers(0), m_bAllowAsyncTransactions(false), m_iStmtIndex(-1), m_logSQL(false), m_pingIntervallms(0) { m_nQueryCounter = -1; @@ -324,27 +324,26 @@ class Database //connection helper counters int m_nQueryConnPoolSize; //current size of query connection pool - ACE_Atomic_Op m_nQueryCounter; //counter for connection selection + std::atomic m_nQueryCounter; //counter for connection selection //lets use pool of connections for sync queries typedef std::vector< SqlConnection* > SqlConnectionContainer; SqlConnectionContainer m_pQueryConnections; SqlQueue* m_delayQueue; - SqlQueue** m_serialDelayQueue; // simple mapping for worker ID -> serialized queue (only executed in set worker thread) SqlConnection* m_pAsyncConn; SqlResultQueue* m_pResultQueue; ///< Transaction queues from diff. threads uint32 m_numAsyncWorkers; - SqlDelayThread** m_threadsBodies; ///< Pointer to delay sql executer (owned by m_delayThread) - ACE_Based::Thread** m_delayThreads; ///< Pointer to executer thread + std::vector> m_threadsBodies; ///< Pointer to delay sql executer (owned by m_delayThread) + std::vector m_delayThreads; ///< Pointer to executer thread bool m_bAllowAsyncTransactions; ///< flag which specifies if async transactions are enabled //PREPARED STATEMENT REGISTRY - typedef ACE_Thread_Mutex LOCK_TYPE; - typedef ACE_Guard LOCK_GUARD; + using LOCK_TYPE = std::mutex; + using LOCK_GUARD = std::unique_lock ; mutable LOCK_TYPE m_stmtGuard; diff --git a/src/shared/Database/DatabaseMysql.cpp b/src/shared/Database/DatabaseMysql.cpp index c8fd0c009..b12c5e786 100644 --- a/src/shared/Database/DatabaseMysql.cpp +++ b/src/shared/Database/DatabaseMysql.cpp @@ -26,7 +26,6 @@ #include "Util.h" #include "Policies/SingletonImp.h" #include "Platform/Define.h" -#include "Threading.h" #include "DatabaseEnv.h" #include "Timer.h" diff --git a/src/shared/Database/DatabaseMysql.h b/src/shared/Database/DatabaseMysql.h index 1ec633072..6c5cfb9a0 100644 --- a/src/shared/Database/DatabaseMysql.h +++ b/src/shared/Database/DatabaseMysql.h @@ -27,8 +27,6 @@ //#include "Common.h" #include "Database.h" #include "Policies/Singleton.h" -#include "ace/Thread_Mutex.h" -#include "ace/Guard_T.h" #ifdef WIN32 #include diff --git a/src/shared/Database/DatabasePostgre.cpp b/src/shared/Database/DatabasePostgre.cpp index 9b45b26e2..7e3eda4b9 100644 --- a/src/shared/Database/DatabasePostgre.cpp +++ b/src/shared/Database/DatabasePostgre.cpp @@ -24,7 +24,6 @@ #include "Util.h" #include "Policies/SingletonImp.h" #include "Platform/Define.h" -#include "Threading.h" #include "DatabaseEnv.h" #include "Database/SqlOperations.h" #include "Timer.h" diff --git a/src/shared/Database/DatabasePostgre.h b/src/shared/Database/DatabasePostgre.h index 55afc00e3..0c3c467c2 100644 --- a/src/shared/Database/DatabasePostgre.h +++ b/src/shared/Database/DatabasePostgre.h @@ -25,8 +25,6 @@ #include "Common.h" #include "Database.h" #include "Policies/Singleton.h" -#include "ace/Thread_Mutex.h" -#include "ace/Guard_T.h" #include #ifdef WIN32 diff --git a/src/shared/Database/SqlDelayThread.cpp b/src/shared/Database/SqlDelayThread.cpp index af2a2ae6e..94c57694e 100644 --- a/src/shared/Database/SqlDelayThread.cpp +++ b/src/shared/Database/SqlDelayThread.cpp @@ -23,8 +23,8 @@ #include "Database/SqlOperations.h" #include "DatabaseEnv.h" -SqlDelayThread::SqlDelayThread(Database* db, SqlConnection* conn, int workerId) - : m_dbEngine(db), m_dbConnection(conn), m_running(true), m_workerId(workerId) +SqlDelayThread::SqlDelayThread(Database* db, SqlConnection* conn) + : m_dbEngine(db), m_dbConnection(conn), m_running(true) { } @@ -35,6 +35,16 @@ SqlDelayThread::~SqlDelayThread() delete m_dbConnection; } +void SqlDelayThread::addSerialOperation(SqlOperation *op) +{ + m_serialDelayQueue.add(op); +} + +bool SqlDelayThread::HasAsyncQuery() +{ + return !m_serialDelayQueue.empty_unsafe(); +} + void SqlDelayThread::run() { #ifndef DO_POSTGRESQL @@ -50,7 +60,7 @@ void SqlDelayThread::run() { // if the running state gets turned off while sleeping // empty the queue before exiting - ACE_Based::Thread::Sleep(loopSleepms); + std::this_thread::sleep_for(std::chrono::milliseconds(loopSleepms)); ProcessRequests(); @@ -83,7 +93,7 @@ void SqlDelayThread::ProcessRequests() } // Process any serial operations for this worker - while (m_dbEngine->NextSerialDelayedOperation(m_workerId, s)) + while (m_serialDelayQueue.next(s)) { s->Execute(m_dbConnection); delete s; diff --git a/src/shared/Database/SqlDelayThread.h b/src/shared/Database/SqlDelayThread.h index b3ca6e64f..e921803aa 100644 --- a/src/shared/Database/SqlDelayThread.h +++ b/src/shared/Database/SqlDelayThread.h @@ -22,38 +22,38 @@ #ifndef __SQLDELAYTHREAD_H #define __SQLDELAYTHREAD_H -#include "ace/Thread_Mutex.h" #include "LockedQueue.h" -#include "Threading.h" class Database; class SqlOperation; class SqlConnection; -class SqlDelayThread : public ACE_Based::Runnable +class SqlDelayThread { - typedef ACE_Based::LockedQueue SqlQueue; + typedef LockedQueue SqlQueue; private: SqlQueue m_sqlQueue; ///< Queue of SQL statements - Database* m_dbEngine; ///< Pointer to used Database engine - SqlConnection* m_dbConnection; ///< Pointer to DB connection + Database *m_dbEngine; ///< Pointer to used Database engine + SqlQueue m_serialDelayQueue; + SqlConnection *m_dbConnection; ///< Pointer to DB connection volatile bool m_running; - int m_workerId; //process all enqueued requests void ProcessRequests(); public: - SqlDelayThread(Database* db, SqlConnection* conn, int workerId); - ~SqlDelayThread() override; + SqlDelayThread(Database* db, SqlConnection* conn); + ~SqlDelayThread(); ///< Put sql statement to delay queue bool Delay(SqlOperation* sql) { m_sqlQueue.add(sql); return true; } + void addSerialOperation(SqlOperation *op); + bool HasAsyncQuery(); virtual void Stop(); ///< Stop event - void run() override; ///< Main Thread loop + void run(); ///< Main Thread loop }; #endif //__SQLDELAYTHREAD_H diff --git a/src/shared/Database/SqlOperations.cpp b/src/shared/Database/SqlOperations.cpp index 25ba252f8..df0945b36 100644 --- a/src/shared/Database/SqlOperations.cpp +++ b/src/shared/Database/SqlOperations.cpp @@ -24,6 +24,7 @@ #include "DatabaseEnv.h" #include "DatabaseImpl.h" #include "Timer.h" +#include "ThreadPool.h" #define LOCK_DB_CONN(conn) SqlConnection::Lock guard(conn) @@ -100,37 +101,11 @@ bool SqlQuery::Execute(SqlConnection* conn) return true; } -class SqlResultCallbackCaller : public ACE_Based::Runnable -{ - public: - typedef ACE_Based::LockedQueue CallbackQueue; - CallbackQueue queue; - virtual void run() - { - #ifndef DO_POSTGRESQL - mysql_thread_init(); - #endif - MaNGOS::IQueryCallback* s = nullptr; - while (queue.next(s)) - { - s->Execute(); - delete s; - } - #ifndef DO_POSTGRESQL - mysql_thread_end(); - #endif - } -}; - void SqlResultQueue::Update(uint32 timeout) { uint32 begin = WorldTimer::getMSTime(); /// execute the callbacks waiting in the synchronization queue - int threadsCount = 6; - SqlResultCallbackCaller* caller = new SqlResultCallbackCaller(); - caller->incReference(); - ACE_Based::Thread** threads = new ACE_Based::Thread*[threadsCount]; - MaNGOS::IQueryCallback* callback = nullptr; + MaNGOS::IQueryCallback* callback = NULL; int n = 0; while (next(callback)) { @@ -142,15 +117,15 @@ void SqlResultQueue::Update(uint32 timeout) else { ++n; - caller->queue.add(callback); + //caller->queue.add(callback); + m_callbackThreads << [callback, n](){ + callback->Execute(); + delete callback; + }; } } - if (threadsCount > n) - threadsCount = n; - for (int i = 0; i < threadsCount; ++i) - threads[i] = new ACE_Based::Thread(caller); - // Now execute thread unsafe callbacks - MaNGOS::IQueryCallback* s = nullptr; + std::future job = m_callbackThreads->processWorkload(); + MaNGOS::IQueryCallback* s = NULL; while (_threadUnsafeWaitingQueries.next(s)) { s->Execute(); @@ -163,16 +138,25 @@ void SqlResultQueue::Update(uint32 timeout) if (numUnsafeQueries > 1000) // Bottleneck here sLog.out(LOG_PERFORMANCE, "Database: %u unsafe queries remaining!", numUnsafeQueries); - for (int i = 0; i < threadsCount; ++i) - { - ACE_Based::Thread* t = threads[i]; - t->wait(); - delete t; - } - delete[] threads; - caller->decReference(); + if (job.valid()) + job.wait(); } + +#ifndef DO_POSTGRESQL +using SqlResultQueueWorker = ThreadPool::ThreadPool::MySQL<>; +#else +using SqlResultQueueWorker = ThreadPool::SingleQueue; +#endif + +SqlResultQueue::SqlResultQueue() : + numUnsafeQueries(0), m_callbackThreads(new ThreadPool(6)) +{ + m_callbackThreads->start(); +} + +SqlResultQueue::~SqlResultQueue(){} + void SqlResultQueue::CancelAll() { MaNGOS::IQueryCallback* cb; diff --git a/src/shared/Database/SqlOperations.h b/src/shared/Database/SqlOperations.h index e35c3b554..abe0b7af7 100644 --- a/src/shared/Database/SqlOperations.h +++ b/src/shared/Database/SqlOperations.h @@ -24,10 +24,10 @@ #include "Common.h" -#include "ace/Thread_Mutex.h" #include "LockedQueue.h" #include #include "Utilities/Callback.h" +#include /// ---- BASE --- @@ -97,15 +97,19 @@ class SqlResultQueue; /// queue for thread class SqlQueryHolder; /// groups several async quries class SqlQueryHolderEx; /// points to a holder, added to the delay thread -class SqlResultQueue : public ACE_Based::LockedQueue +class ThreadPool; + +class SqlResultQueue : public LockedQueue { public: - SqlResultQueue() : numUnsafeQueries(0) {} + SqlResultQueue(); + ~SqlResultQueue(); void CancelAll(); void Update(uint32 maxTime); - typedef ACE_Based::LockedQueue CallbackQueue; + typedef LockedQueue CallbackQueue; CallbackQueue _threadUnsafeWaitingQueries; uint32 numUnsafeQueries; + std::unique_ptr m_callbackThreads; }; class SqlQuery : public SqlOperation diff --git a/src/shared/DelayExecutor.cpp b/src/shared/DelayExecutor.cpp index 76e27223a..95213a704 100644 --- a/src/shared/DelayExecutor.cpp +++ b/src/shared/DelayExecutor.cpp @@ -16,15 +16,20 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -#include -#include #include #include "DelayExecutor.h" +#include "Policies/SingletonImp.h" +#include "Policies/ThreadingModel.h" + + +using DelayExecutorLock = MaNGOS::ClassLevelLockable; +INSTANTIATE_SINGLETON_2(DelayExecutor, DelayExecutorLock); +INSTANTIATE_CLASS_MUTEX(DelayExecutor, std::mutex); DelayExecutor* DelayExecutor::instance() { - return ACE_Singleton::instance(); + return &MaNGOS::Singleton::Instance(); } DelayExecutor::DelayExecutor() @@ -119,4 +124,4 @@ bool DelayExecutor::activated() void DelayExecutor::activated(bool s) { activated_ = s; -} \ No newline at end of file +} diff --git a/src/shared/LockedQueue.h b/src/shared/LockedQueue.h index 57cfa0999..4b5a49e6d 100644 --- a/src/shared/LockedQueue.h +++ b/src/shared/LockedQueue.h @@ -22,122 +22,118 @@ #ifndef LOCKEDQUEUE_H #define LOCKEDQUEUE_H -#include -#include #include +#include #include #include "Errors.h" -namespace ACE_Based +template > + class LockedQueue { - template > - class LockedQueue - { - //! Lock access to the queue. - LockType _lock; + //! Lock access to the queue. + LockType _lock; - //! Storage backing the queue. - StorageType _queue; + //! Storage backing the queue. + StorageType _queue; - //! Cancellation flag. - /*volatile*/ bool _canceled; + //! Cancellation flag. + /*volatile*/ bool _canceled; - public: + public: - //! Create a LockedQueue. - LockedQueue() - : _canceled(false) - { - } + //! Create a LockedQueue. + LockedQueue() + : _canceled(false) + { + } - //! Destroy a LockedQueue. - virtual ~LockedQueue() - { - } + //! Destroy a LockedQueue. + virtual ~LockedQueue() + { + } - //! Adds an item to the queue. - void add(T const& item) - { - ACE_Guard g(this->_lock); - _queue.push_back(item); - } + //! Adds an item to the queue. + void add(const T& item) + { + std::unique_lock g(this->_lock); + _queue.push_back(item); + } - //! Gets the next result in the queue, if any. - bool next(T& result) - { - ACE_GUARD_RETURN (LockType, g, this->_lock, false); + //! Gets the next result in the queue, if any. + bool next(T& result) + { + std::unique_lock g(this->_lock); - if (_queue.empty()) - return false; + if (_queue.empty()) + return false; - result = _queue.front(); - _queue.pop_front(); + result = _queue.front(); + _queue.pop_front(); - return true; - } + return true; + } - template - bool next(T& result, Checker& check) - { - ACE_GUARD_RETURN (LockType, g, this->_lock, false); + template + bool next(T& result, Checker& check) + { + std::unique_lock g(this->_lock); - if (_queue.empty()) - return false; + if (_queue.empty()) + return false; - result = _queue.front(); - if(!check.Process(result)) - return false; + result = _queue.front(); + if(!check.Process(result)) + return false; - _queue.pop_front(); - return true; - } + _queue.pop_front(); + return true; + } - //! Peeks at the top of the queue. Remember to unlock after use. - T& peek() - { - lock(); + //! Peeks at the top of the queue. Remember to unlock after use. + T& peek() + { + lock(); - T& result = _queue.front(); + T& result = _queue.front(); - return result; - } + return result; + } - //! Cancels the queue. - void cancel() - { - ACE_Guard g(this->_lock); - _canceled = true; - } + //! Cancels the queue. + void cancel() + { + std::unique_lock g(this->_lock); + _canceled = true; + } - //! Checks if the queue is cancelled. - bool cancelled() - { - ACE_Guard g(this->_lock); - return _canceled; - } + //! Checks if the queue is cancelled. + bool cancelled() + { + std::unique_lock g(this->_lock); + return _canceled; + } - //! Locks the queue for access. - void lock() - { - this->_lock.acquire(); - } + //! Locks the queue for access. + void lock() + { + this->_lock.lock(); + } - //! Unlocks the queue. - void unlock() - { - this->_lock.release(); - } + //! Unlocks the queue. + void unlock() + { + this->_lock.unlock(); + } - bool empty_unsafe() - { - return _queue.empty(); - } - ///! Checks if we're empty or not with locks held - bool empty() - { - ACE_Guard g(this->_lock); - return _queue.empty(); - } - }; -} + bool empty_unsafe() + { + return _queue.empty(); + } + ///! Checks if we're empty or not with locks held + bool empty() + { + std::unique_lock g(this->_lock); + return _queue.empty(); + } +}; #endif diff --git a/src/shared/Log.h b/src/shared/Log.h index cd0dd28fb..4913110c1 100644 --- a/src/shared/Log.h +++ b/src/shared/Log.h @@ -117,7 +117,7 @@ enum LogType int const Color_count = int(WHITE)+1; -class Log : public MaNGOS::Singleton > +class Log : public MaNGOS::Singleton > { friend class MaNGOS::OperatorNew; Log(); diff --git a/src/shared/ThreadPool.cpp b/src/shared/ThreadPool.cpp new file mode 100644 index 000000000..6f3e588ef --- /dev/null +++ b/src/shared/ThreadPool.cpp @@ -0,0 +1,277 @@ +/* + * Copyright (C) 2017 Elysium Project + * + * 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 + */ + +#include "ThreadPool.h" +#include "Log.h" +#include + +#ifdef WIN32 +#undef ERROR +#undef IGNORE +#endif + +ThreadPool::ThreadPool(int numThreads, ClearMode when, ErrorHandling mode) : + m_errorHandling(mode), m_size(numThreads), m_clearMode(when), m_active(0) +{ + m_workers.reserve(m_size); +} + +ThreadPool::~ThreadPool() +{ + std::unique_lock lock(m_mutex); + m_status = Status::TERMINATING; + m_waitForWork.notify_all(); +} + +std::future ThreadPool::processWorkload(Callable pre, Callable post) +{ + if (m_clearMode == ClearMode::AT_NEXT_WORKLOAD && + m_status == Status::READY && m_dirty) + clearWorkload(); + if (m_status != Status::READY || m_workload.empty()) + return std::future(); + m_result = std::promise(); + m_dirty = true; + m_active = std::min(m_size, m_workload.size()); + m_index = 0; + m_status = Status::PROCESSING; + std::unique_lock lock(m_mutex); + for (int i = 0; i < m_active; i++) + m_workers[i]->prepare(pre, post); + m_waitForWork.notify_all(); + return m_result.get_future(); +} + +std::future ThreadPool::processWorkload(workload_t &workload, Callable pre, Callable post) +{ + if (m_status != Status::READY) + return std::future(); + m_workload = workload; + m_dirty = false; + return processWorkload(pre, post); +} + +std::future ThreadPool::processWorkload(workload_t &&workload, Callable pre, Callable post) +{ + if (m_status != Status::READY) + return std::future(); + m_workload = std::move(workload); + m_dirty = false; + return processWorkload(pre, post); +} + +ThreadPool::Status ThreadPool::status() const +{ + return m_status; +} + +size_t ThreadPool::size() const +{ + return m_size; +} + +std::vector ThreadPool::taskErrors() const +{ + return m_errors; +} + +void ThreadPool::worker::waitForWork() +{ + std::shared_lock lock(pool->m_mutex); //locked! + while(!busy && pool->status() != Status::TERMINATING) //wait for work + pool->m_waitForWork.wait(lock); +} + +ThreadPool &ThreadPool::operator<<(Callable packaged_task) +{ + if (m_status == Status::PROCESSING || m_status == Status::ERROR) + throw "Attempt to append a task to a load being processed!"; + if (m_clearMode == ClearMode::AT_NEXT_WORKLOAD && m_dirty) + clearWorkload(); + m_workload.emplace_back(packaged_task); + return *this; +} + +void ThreadPool::clearWorkload() +{ + m_dirty = false; + m_workload.clear(); +} + +ThreadPool::worker::worker(ThreadPool *pool, int id, ThreadPool::ErrorHandling mode) : + id(id), errorHandling(mode), pool(pool), thread([this](){this->loop_wrapper();}) +{ +} + +ThreadPool::worker::~worker() +{ + thread.join(); +} + +void ThreadPool::worker::loop_wrapper() +{ + if (pool->m_errorHandling == ErrorHandling::NONE) + loop(); + else + { + std::exception_ptr err_p; + try + { + loop(); + } + catch (...) + { + + err_p = std::current_exception(); + } + + if (pool->m_errorHandling == ErrorHandling::IGNORE) + { + if (pool->status() == Status::TERMINATING) + return; + loop_wrapper(); + return; + } + try{ + if (err_p) + { + pool->m_errors.push_back(err_p); + std::rethrow_exception(err_p); + } + } + catch (const std::exception &e) + { + sLog.outError("A ThreadPool task generated an exception: %s",e.what()); + } + catch (const std::string &e) + { + sLog.outError("A ThreadPool task generated an exception: %s", e.c_str()); + } + catch (...) + { + sLog.outError("A ThreadPool task generated an exception"); + } + if (pool->m_errorHandling == ErrorHandling::TERMINATE) + pool->m_status = Status::TERMINATING; + if (pool->status() == Status::TERMINATING) + return; + loop_wrapper(); + } +} + +void ThreadPool::worker::prepare(ThreadPool::Callable pre, ThreadPool::Callable post) +{ + busy = true; + this->pre = pre; + this->post = post; +} + +void ThreadPool::worker::loop() +{ + while(true) + { + waitForWork(); + if (pool->m_status == Status::TERMINATING) + return; + + if (pre) + pre(); + + doWork(); + + if (post) + post(); + + busy = false; + int remaning = --(pool->m_active); + if (!remaning) + { + if (pool->m_clearMode == ClearMode::UPPON_COMPLETION) + pool->clearWorkload(); + if (pool->m_status == Status::ERROR) + { + pool->m_status = Status::READY; + pool->m_result.set_exception(pool->m_errors.front()); + } + else + { + pool->m_status = Status::READY; + pool->m_result.set_value(); + } + } + } +} + +ThreadPool::worker_mq::worker_mq(ThreadPool *pool, int id, ThreadPool::ErrorHandling mode) : + worker(pool,id,mode) +{ +} + +void ThreadPool::worker_mq::doWork() +{ + while (it < pool->m_workload.size() && pool->m_status == Status::PROCESSING) + { + int w = it; + it += pool->m_size; //if it fails, we might want to skip this task. + pool->m_workload[w](); + } +} + +void ThreadPool::worker_mq::prepare(ThreadPool::Callable pre, ThreadPool::Callable post) +{ + it = id; + worker::prepare(pre, post); +} + +ThreadPool::worker_sq::worker_sq(ThreadPool *pool, int id, ThreadPool::ErrorHandling mode) : + worker(pool,id,mode) +{ +} + +void ThreadPool::worker_sq::doWork() +{ + int i = pool->m_index++; + while (i < pool->m_workload.size() && pool->m_status == Status::PROCESSING) + { + pool->m_workload[i](); + i = pool->m_index++; + } +} + +template +ThreadPool::worker_mysql::worker_mysql(ThreadPool *tp, int id, ThreadPool::ErrorHandling e): + T(tp, id, e) +{ +} + +template +void ThreadPool::worker_mysql::doWork() +{ + mysql_thread_init(); + T::doWork(); + mysql_thread_end(); +} + + +template struct ThreadPool::worker_mysql; +template struct ThreadPool::worker_mysql; + +template void ThreadPool::start(); +template void ThreadPool::start(); +template void ThreadPool::start>(); +template void ThreadPool::start>(); diff --git a/src/shared/ThreadPool.h b/src/shared/ThreadPool.h new file mode 100644 index 000000000..4af6c4302 --- /dev/null +++ b/src/shared/ThreadPool.h @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2017 Elysium Project + * + * 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 + */ + +#ifndef THREADPOOL_H +#define THREADPOOL_H + +#include +#include +#include +#include +#include +#include +#include + +#ifdef WIN32 +#undef ERROR +#undef IGNORE +#endif + +class ThreadPool +{ +private: + struct worker_sq; + struct worker_mq; + template + struct worker_mysql; +public: + using SingleQueue = worker_sq; + using MultiQueue = worker_mq; + template + using MySQL = worker_mysql; + + using Callable = std::function; + + using workload_t = std::vector; + + enum class Status { + ERROR = -1, + STOPPED, + STARTING, + READY, + PROCESSING, + TERMINATING + }; + + enum class ClearMode { + NEVER, + UPPON_COMPLETION, + AT_NEXT_WORKLOAD + }; + + /** + * @brief The ErrorHandling enum defines how the workers will manage tasks generating exceptions + * NONE: the error will propagate + * IGNORE: skip the current task + * LOG: skip the current task, logs the error + * TERMINATE: skip all remaning tasks + */ + enum class ErrorHandling { + NONE, + IGNORE, + LOG, + TERMINATE + }; + + /** + * @brief ThreadPool allocates memory, use ThreadPool::start() to spawn the threads. + * @param numThreads the number of threads that will be created. + */ + ThreadPool(int numThreads, ClearMode when = ClearMode::AT_NEXT_WORKLOAD, ErrorHandling mode = ErrorHandling::NONE); + + ThreadPool() = delete; + + ~ThreadPool(); + + /** + * @brief start creates and start the treads. + */ + template + void start() + { + if (m_status != Status::STOPPED || !m_size) + return; + m_status = Status::STARTING; + for (int i = 0; i < m_size; i++) + m_workers.emplace_back(new WORKER_T(this, i, m_errorHandling)); + m_status = Status::READY; + } + + /** + * @brief processWorkload notify the threads that the workload is ready. + */ + std::future processWorkload(Callable pre = Callable(), Callable post = Callable()); + + /** + * @brief setWorkload set the next workload + * @param workload + * @param safe if true, it will wait for previous workload to be done + */ + std::future processWorkload(workload_t &workload, Callable pre = Callable(), Callable post = Callable()); + std::future processWorkload(workload_t &&workload,Callable pre = Callable(), Callable post = Callable()); + + /** + * @brief status + * @return the current status + */ + Status status() const; + + /** + * @brief size + * @return the number of threads that are/will be created + */ + size_t size() const; + + /** + * @brief taskErrors always return an empty vector if ErrorHandling was set to IGNORE + * @return a vector containing all task exceptions generated during last processed workload + */ + std::vector taskErrors() const; + + /** + * @brief operator << add a task to the workload + * NOT threadsafe + * @param function + * @return + */ + ThreadPool& operator<<(Callable function); + + /** + * @brief clearWorkload + * clear the current workload + * WARNING: NOT threadsafe, call waitForFinished() first + */ + void clearWorkload(); + +private: + struct worker { + worker(ThreadPool *pool, int id, ErrorHandling mode); + ~worker(); + + void loop_wrapper(); + void loop(); + virtual void doWork() = 0; + virtual void prepare(Callable pre, Callable post); + void waitForWork(); + + int id; + ErrorHandling errorHandling; + volatile bool busy = false; + ThreadPool *pool; + std::thread thread; + Callable pre, post; + + }; + + struct worker_sq : public worker{ + worker_sq(ThreadPool *pool, int id, ErrorHandling mode); + + void doWork() override; + }; + + struct worker_mq : public worker{ + worker_mq(ThreadPool *pool, int id, ErrorHandling mode); + + void doWork() override; + void prepare(Callable pre, Callable post) override; + + int it; + }; + + template + struct worker_mysql : public T + { + worker_mysql(ThreadPool *tp, int id, ErrorHandling e); + + void doWork() override; + }; + + using workers_t = std::vector>; + + Status m_status = Status::STOPPED; + ErrorHandling m_errorHandling; + size_t m_size; + std::shared_timed_mutex m_mutex; + std::condition_variable_any m_waitForWork; + workload_t m_workload; + ClearMode m_clearMode; + bool m_dirty = false; + std::atomic m_active; + std::atomic m_index; + std::vector m_errors; + std::promise m_result; + workers_t m_workers; +}; + +template +std::unique_ptr & operator<<(std::unique_ptr & tp, T &&f) +{ + (*tp) << std::forward(f); + return tp; +} + +#endif diff --git a/src/shared/Threading.cpp b/src/shared/Threading.cpp deleted file mode 100644 index 1b15d805e..000000000 --- a/src/shared/Threading.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (C) 2005-2011 MaNGOS - * Copyright (C) 2009-2011 MaNGOSZero - * Copyright (C) 2011-2016 Nostalrius - * Copyright (C) 2016-2017 Elysium Project - * - * 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 - */ - -#include "Threading.h" -#include "Errors.h" -#include -#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(); - } - - //MANGOS_ASSERT (!_tmp.empty()); - - if(_tmp.size() >= MAXPRIORITYNUM) - { - size_t const 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; - } - } - - //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 - size_t const _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]; -} - -#ifndef __sun__ -# define THREADFLAG (THR_NEW_LWP | THR_JOINABLE | THR_SCHED_DEFAULT) -#else -# define THREADFLAG (THR_NEW_LWP | THR_JOINABLE) -#endif - -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(); - //MANGOS_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; - - 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 - Runnable* task = m_task; - m_task = nullptr; - task->decReference(); // Prevent race conditions, because at this point, m_task may be deleted! -} - -void Thread::suspend() -{ - ACE_Thread::suspend(m_hThreadHandle); -} - -void Thread::resume() -{ - ACE_Thread::resume(m_hThreadHandle); -} - -ACE_THR_FUNC_RETURN Thread::ThreadTask(void* param) -{ - unsigned int seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); - srand(seed); - - Runnable * _task = (Runnable*)param; - _task->incReference(); - _task->run(); - - // task execution complete, free referecne added at - _task->decReference(); // for the last incReference - _task->decReference(); // cf Thread::start - - 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); - delete _oldValue; - } - - return _thread; -} - -void Thread::setPriority(Priority type) -{ -#ifndef __sun__ - 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 - //MANGOS_ASSERT (_ok == 0); -#endif -} - -void Thread::Sleep(unsigned long msecs) -{ - ACE_OS::sleep(ACE_Time_Value(0, 1000 * msecs)); -} diff --git a/src/shared/Threading.h b/src/shared/Threading.h deleted file mode 100644 index a0f8788e0..000000000 --- a/src/shared/Threading.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2005-2011 MaNGOS - * Copyright (C) 2009-2011 MaNGOSZero - * Copyright (C) 2011-2016 Nostalrius - * Copyright (C) 2016-2017 Elysium Project - * - * 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 - */ - -#ifndef THREADING_H -#define THREADING_H - -#include -#include -#include "ace/Atomic_Op.h" -#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); - void setTask(Runnable* instance) { m_task = 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(Thread const&); - Thread& operator=(Thread const&); - - 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