I have a server which is built in a thread-per-client way. Lately, I bumped into a problem that I'm having a really hard time to come up with a solution to, so I thought to ask some help.
My server hosts a lobby, in the lobby there are many rooms (all of them owned by users), and in rooms there are players. Each room has an admin, when the admin chooses to leave - the room is closed, and all of the users are supposed to return to the lobby.
Now, I already have a working code - but there's the problem, I have no idea how should I have the other clients also exiting from the room. The code running in the thread is as following:
while(in_lobby)
{
//Receive a message
//Do stuff
//In certain cases change the Boolean to fit to the situation
//Send a comeback
}
while(in_room)
{
//Receive a message
//Do stuff
//In certain cases change the Boolean to fit to the situation
//Send a comeback
}
while(in_game)
{
//When a game started
//Not practical right now, though
}
There is no problem messing with the booleans from a thread of one client to another (because they are not exactly local variables, they are several conditions that I could change through the thread which is handling the administrator choosing to close the room).
The problem occurs when the condition DOES change, and the while loop is supposed to exit before the next iteration. Why does it occur? Because in the beginning of the iteration there's a recv()
call, which awaits the client's messages.
Now, the condition is okay, everything is okay, but the loop won't continue (so it won't reach the next iteration - to see that the condition is false) until the server receives a certain message from the client (which it shouldn't, because closing the room doesn't depend on a regular user - the user only receives and alert, which is also sent through the admin's thread, about the room being closed).
My question therefore is:
How can I perform what I want? How can I make these users to break out of the loop, returning to the lobby (there is no problem with doing so with the admin, as his thread is the one that does everything and he returns to the lobby successfully) without changing the whole architecture from a thread-per-client way?