Skip to content

Commit

Permalink
fix: do not cache lastReceived in release
Browse files Browse the repository at this point in the history
When building release mode,  the compiler could theoretically
catch the lastReceived value.

By using VolatileRead, we can ensure this is not the case
and make sure we get an up to date value for it
  • Loading branch information
paulpach committed Nov 3, 2020
1 parent b25a1f6 commit 9a15863
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions Assets/Mirror/Runtime/Transport/Kcp/KcpConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Cysharp.Threading.Tasks;
using Debug = UnityEngine.Debug;

Expand Down Expand Up @@ -62,7 +63,6 @@ protected void SetupKcp()

kcp.SetNoDelay(delayMode);
open = true;
lastReceived = stopWatch.ElapsedMilliseconds;

Tick().Forget();
}
Expand All @@ -71,10 +71,13 @@ async UniTaskVoid Tick()
{
try
{
Thread.VolatileWrite(ref lastReceived, stopWatch.ElapsedMilliseconds);

while (open )
{
long now = stopWatch.ElapsedMilliseconds;
if (now > lastReceived + Timeout)
long received = Thread.VolatileRead(ref lastReceived);
if (now > received + Timeout)
break;

kcp.Update((uint)now);
Expand Down Expand Up @@ -132,7 +135,7 @@ internal void RawInput(byte[] buffer, int msgLength)
private void InputUnreliable(byte[] buffer, int msgLength)
{
unreliable.Input(buffer, msgLength);
lastReceived = stopWatch.ElapsedMilliseconds;
Thread.VolatileWrite(ref lastReceived, stopWatch.ElapsedMilliseconds);

if (isWaiting && unreliable.PeekSize() > 0)
{
Expand All @@ -144,7 +147,7 @@ private void InputReliable(byte[] buffer, int msgLength)
{
kcp.Input(buffer, msgLength);

lastReceived = stopWatch.ElapsedMilliseconds;
Thread.VolatileWrite(ref lastReceived, stopWatch.ElapsedMilliseconds);

if (isWaiting && kcp.PeekSize() > 0)
{
Expand Down

0 comments on commit 9a15863

Please sign in to comment.