Skip to content

Commit

Permalink
+ Add LockGuard class (#49)
Browse files Browse the repository at this point in the history
+ Replace usage of SpinLock.Unlock() and SpinLock.Lock() with LockGuard
  • Loading branch information
noSTALKER authored and MaggieQi committed Jun 4, 2019
1 parent 7311ee5 commit 0b85256
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 12 deletions.
22 changes: 22 additions & 0 deletions AnnService/inc/Helper/Concurrent.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,28 @@ class SpinLock
std::atomic_flag m_lock = ATOMIC_FLAG_INIT;
};

template<typename Lock>
class LockGuard {
public:
LockGuard(Lock& lock) noexcept
: m_lock(lock) {
lock.Lock();
}

LockGuard(Lock& lock, std::adopt_lock_t) noexcept
: m_lock(lock) {}

~LockGuard() {
m_lock.Unlock();
}

LockGuard(const LockGuard&) = delete;
LockGuard& operator=(const LockGuard&) = delete;

private:
Lock& m_lock;
};


class WaitSignal
{
Expand Down
25 changes: 13 additions & 12 deletions AnnService/src/Socket/ConnectionManager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@ ConnectionManager::AddConnection(boost::asio::ip::tcp::socket&& p_socket,
p_handler,
std::weak_ptr<ConnectionManager>(shared_from_this()));

m_spinLock.Lock();
m_connections[GetPosition(currID)].m_connection = connection;
m_spinLock.Unlock();
{
Helper::Concurrent::LockGuard<Helper::Concurrent::SpinLock> guard(m_spinLock);
m_connections[GetPosition(currID)].m_connection = connection;
}

connection->Start();
if (p_heartbeatIntervalSeconds > 0)
Expand All @@ -67,9 +68,10 @@ ConnectionManager::RemoveConnection(ConnectionID p_connectionID)

Connection::Ptr conn;

m_spinLock.Lock();
conn = std::move(m_connections[position].m_connection);
m_spinLock.Unlock();
{
Helper::Concurrent::LockGuard<Helper::Concurrent::SpinLock> guard(m_spinLock);
conn = std::move(m_connections[position].m_connection);
}

--m_connectionCount;

Expand All @@ -89,9 +91,10 @@ ConnectionManager::GetConnection(ConnectionID p_connectionID)
auto position = GetPosition(p_connectionID);
Connection::Ptr ret;

m_spinLock.Lock();
ret = m_connections[position].m_connection;
m_spinLock.Unlock();
{
Helper::Concurrent::LockGuard<Helper::Concurrent::SpinLock> guard(m_spinLock);
ret = m_connections[position].m_connection;
}

if (nullptr == ret || ret->GetConnectionID() != p_connectionID)
{
Expand All @@ -112,16 +115,14 @@ ConnectionManager::SetEventOnRemoving(std::function<void(ConnectionID)> p_event)
void
ConnectionManager::StopAll()
{
m_spinLock.Lock();
Helper::Concurrent::LockGuard<Helper::Concurrent::SpinLock> guard(m_spinLock);
for (auto& connection : m_connections)
{
if (nullptr != connection.m_connection)
{
connection.m_connection->Stop();
}
}

m_spinLock.Unlock();
}


Expand Down

0 comments on commit 0b85256

Please sign in to comment.