Hi
Been a while since I posted, been busy programning my new RTS game or in fact it is rather a TBS/RTS hybrid.
Anyway, since it uses a peer2peer system (will later convert it to a combination of client server and peer2peer with a web server) I am dealing with thread safety. As of now, I have not had any problems but I only tried it 3 players so far, if game will have 10-20 players problems might show up that I do not yet have realised. So, I am going to check with others here if my method is correct or if I already need to design something better.
Now, here is how the HOST player works.
It has an orderqueue, basically a class basically like a vector but it decodes the strings you have put into the vector to something useful for the game i.e. an action that is to be performed. A “a 129 133” for example could be decoded as to attack from hex 129 to hex 133 or in code be using like game.resolvebattle(129, 133, blablabla some parameters needed here). So the orderqueue is used by game and the game uses it like a queue so it removes the first element and performs that action (for example might be someone that says "I move my Militia from 30, 30 to 30, 35).
Any requested order in game results to sending into the HOST orderqueue. So there is one queue per game session with say up to 16 players and it is positioned in the host player game. An order means for example move unit or attack or purchase a unit or deploy unit or declare war, …, etc…
Now, the threads that are used for the socket connections (one socket per client by the way) gets incoming strings and put them into the orderqueue.
I heard that Vector is thread safe but that it is also not 100% thread safe, Meaning, if I do orderqueue.get(0) and say that there is only one object in it and someone else does orderqueue.remove(0) at the same time if I am unlucky the remove is done first and the get results in exception.
BUT, the fine thing is all the incoming traffic result in the add method and only the one thread on the host game will remove anything from queue. This means, there are several thread adding into the queue but only ONE thread running that will ever remove anything from the queue, so is this combination thread safe?