1
\$\begingroup\$

I'm working on a multiplayer game and it's currently set up like this. It accepts packets from the client on the fly and does whatever processing it needs to. There is also a main game tick which is set up like so:

for every online player
    update every player in the region

for every online player
    reset flags

The problem I see that can happen is that since it handles packets on the fly, it may modify something between the updating and the flag reset, which could cause it to completely ignore something. I don't think it's possible to synchronize it using the actual synchronize block since it can't update and reset flags at the same time - it needs to reset flags after it updates every player.

The only solution I see is not processing packets on the fly and doing it in the main loop, but this could hurt performance. Is this the best solution, or is there another option I'm not considering?

Thanks

\$\endgroup\$
1
\$\begingroup\$

Welcome to the beautiful world of thread safety and race conditions. The problem you see is very real and a nasty source of impossible to reproduce bugs.

A solution I am using is to not process received network messages immediately. Instead, I have the network system add all received input events into a synchronized list.

One step of the general update loop is then to process that list in a synchronized block and clear it afterwards:

synchronized(messageList) {         
     for (Message message: messageList) {
          // process message
     }
     messageList.clear();
}

As long as one thread is in a synchronized block for a specific object, any other threads who try to enter a synchronized block for the same object (which they will do inside the add method of a synchronized list) will wait until that thread is finished. So no network events will be pushed while the message queue is being processed and cleared. Those events will be pushed afterwards and will then be the first to get processed in the next update tick.

That way you process all of your network events at a controlled point of your update method and avoid any race conditions caused by network events being processed at an unexpected moment.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.