Closed JimViebke closed 7 years ago
The problem with having this run as a background thread is that no safe shutdown mechanism exists on the server, specifically the background thread.
If the server is shut down while a room is being saved, it could corrupt the room's save file.
Consider having a widely-accessible boolean (atomic?) that is an "active" flag (perhaps game_running
). Every thread that works with files or state must periodically (perhaps once per second) check this flag. If the flag is disabled, the thread must finish its necessary work and exit.
Ideally, the thread that disables this flag has the ability to .join()
each thread to know when it's safe to finally terminate the server by calling return;
from the main thread.
Added in dcea5e4.
Implement through the use of a container and a mutex. Note that the container itself does not implement thread-safety, because we want threads to be able to gain control of the mutex just once in order to perform multiple operations.
The container is a sorted datatype where the value is the key. This value is most likely an integer equal to
X*Y_MAX*Z_MAX + Y*Z_MAX + Z
.To unload a room, the client locks the mutex, adds any number of room IDs to the container, then releases the mutex knowing that the room(s) will be unloaded at some later time. This way the client thread (the main thread) never needs to wait for rooms to unload.
On the background thread, the thread locks the mutex, grabs the first element in the container, writes that room to disk, deletes the room from memory, deletes the element from the container, unlocks the mutex, then loops (forever). This thread should have the ability to wait when the container is empty instead of checking in an infinite loop.
To load a room: