Archive

Tag Archives: multithreading

There is a multiplayer server for realtime strategy game.
There is special Process thread to process behaviour of the game world.
It wake up every N milliseconds, do some changes in our object model (game world)
and then sleep for next N milliseconds.
Also, there are asynchronous network actions runned in another Socket thread.
So, the question is about synchronization.

Usually, I use ‘lock (object) { … }’ way to sync. work with data in object model.
There are a lot of locks, so, it needs to keep in mind
this multithreading nature of the server during thinking on the business logic.
As better approach, this time I implemented queue-based solution:
The Process thread may be in 3 modes:
    1) Process the world;
    2) Process the queue of collected actions;
    3) Do nothing.
Depends on the this mode, incoming Socket actions is processing like:
    1) Collected to special queue
    2) Waiting for #2 finish
    3) Process the action directly

Here is pseudocode of both methods (threads), where lock() has C# meaning.

ProcesssIncomingAction(action)
{
    lock (mode)
    {
        if (isProcess)
        {
            lock (queue)
            {
                queue.add(action);
            }
        } else {
            lock (process)
            {
                processAction(action);
            }
        }
    }
}

ProcessObjectModel()
{
    lock (mode)
    {
        isProcess := true;
    }
    lock (process)
    {
        _processObjectModel();
        lock (mode)
        {
            isProcess := false;
        }
        lock (queu)
        {
            processActions(queue);
        }
    }
}

As simpler desing, we can only collect actions in Socket thread
and process them only in the Process thread.
But such solution looks ugly.
In deed, we don’t need to transfer the action via queue,
we need to syncronize the process only.

Advertisements