Sunday, December 16, 2018

multithreading - Can you use a standard multi-thread if only reading unity objects?


First of all I know about coroutines and how to use them (they're awesome).


A friend of mine was telling me about the way the he implemented his saving system in a game he was working on, after asking him what he was using I found out that he is using system.threading and not coroutines to save data.


I know that Unity isn't thread safe but apparently he has had no issues with saving which leads me to wonder if it is ok to use normal threads as long as you're only reading data and no pre-existing data is modified in the gameworld? would this affect the game at all (other than some moving objects being slightly ahead of where they should be because of the time it took to get to that object and save it)?



Answer



Saving in another thread while the game keeps running is dangerous. When the gamestate changes while the savegame file gets written, you will write a mixed gamestate consisting partly of the old state and partly of the new state. This can cause all kinds of weird and impossible to reproduce bugs when that savegame is loaded.


For example, consider you have a script which destroys one game-object and instantiates another in its place. Now consider what happens if the saving takes place exactly between these two operations. There are two possible outcomes: Either both will exist when the savegame is loaded or neither will. Either case might break the game in a way that the player can not continue. You have created the worst nightmare of every gamer: a broken savegame.


The deviousness of such problems is that they will appear completely random. Your friend's savegame system might work perfectly fine in 1000 tests, but at the 1001st time it might run into such a race-condition and screw up. And then never again until after release when the user-reviews of your game are suddenly full of people whining about their corrupted savegames and your testers fall into despair trying to reproduce the problem.


If you want to save in a separate thread, you need to write the complete gamestate to an in-memory data structure first and then start the thread to save that structure while your game keeps running with the original gamestate.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...