Netcode.IO.NET icon indicating copy to clipboard operation
Netcode.IO.NET copied to clipboard

Queue locking strategy error in Client Socket

Open magikworx opened this issue 7 years ago • 1 comments

The queue locking strategy is incorrect for the SocketContext.cs(68-70) call to if (datagramQueue.Count > 0) { packet = datagramQueue.Dequeue(); In a highly concurrent environment, the queue isn't being locked for the entire transaction and a thread can pull an item off the queue making an empty queue when the datagram dequeue is called and causing a System.InvalidOperationException. Maybe you should try to convert this to a CAS style operation or move the storage to a tested concurrent data structure.

magikworx avatar May 27 '18 10:05 magikworx

I changed your DatagramQueue to read as follows

public bool TryDequeue(out Datagram datagram)
{
  lock (queue_mutex){
    if (datagramQueue.Count > 0)
    {
      datagram = datagramQueue.Dequeue();
      return true;
    }  
  }
  datagram = new Datagram();
  return false;
}

The enqueue call in the Pump() should also be updated to use the Enqueue method inside the class and not directly on the queue.

The bonus of TryDequeue is that it simplifies the calls in the SocketContext as follows

public bool Read(out Datagram packet)
{
  return datagramQueue.TryDequeue(out packet);
}

magikworx avatar May 27 '18 11:05 magikworx