Skip to content

Commit

Permalink
fix NetProto thread safety
Browse files Browse the repository at this point in the history
the heartbeat thread could update serverConn at the
same time a loading client wanted to send some data,
e.g. a PE progress packet
  • Loading branch information
rt committed Apr 14, 2019
1 parent 245f660 commit c732a6d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
14 changes: 10 additions & 4 deletions rts/Net/Protocol/NetProtocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,10 @@ float CNetProtocol::GetPacketTime(int frameNum) const
return (gu->startTime + frameNum / (1.0f * GAME_SPEED));
}


std::shared_ptr<const netcode::RawPacket> CNetProtocol::GetData(int frameNum)
{
std::lock_guard<spring::spinlock> lock(serverConnMutex);
std::shared_ptr<const netcode::RawPacket> ret = serverConn->GetData();

if (ret == nullptr)
Expand All @@ -127,15 +129,14 @@ std::shared_ptr<const netcode::RawPacket> CNetProtocol::GetData(int frameNum)
return ret;
}


void CNetProtocol::Send(const netcode::RawPacket* pkt) { Send(std::shared_ptr<const netcode::RawPacket>(pkt)); }
void CNetProtocol::Send(std::shared_ptr<const netcode::RawPacket> pkt)
{
std::lock_guard<spring::spinlock> lock(serverConnMutex);
serverConn->SendData(pkt);
}

void CNetProtocol::Send(const netcode::RawPacket* pkt)
{
Send(std::shared_ptr<const netcode::RawPacket>(pkt));
}

__FORCE_ALIGN_STACK__
void CNetProtocol::UpdateLoop()
Expand All @@ -150,11 +151,16 @@ void CNetProtocol::UpdateLoop()

void CNetProtocol::Update()
{
// any call to clientNet->Send is unsafe while heartbeat thread exists, i.e. during loading
std::lock_guard<spring::spinlock> lock(serverConnMutex);

serverConn->Update();
}

void CNetProtocol::Close(bool flush)
{
std::lock_guard<spring::spinlock> lock(serverConnMutex);

serverConn->Close(flush);
}

Expand Down
3 changes: 3 additions & 0 deletions rts/Net/Protocol/NetProtocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <memory>

#include "BaseNetProtocol.h" // not used in here, but in all files including this one
#include "System/Threading/SpringThreading.h"

class ClientSetup;
class CDemoRecorder;
Expand Down Expand Up @@ -111,6 +112,8 @@ class CNetProtocol
private:
std::atomic<bool> keepUpdating;

spring::spinlock serverConnMutex;

std::unique_ptr<netcode::CConnection> serverConn;
std::unique_ptr<CDemoRecorder> demoRecorder;

Expand Down

0 comments on commit c732a6d

Please sign in to comment.