Thread Used for Saving Causes Frame Drop

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godont

I have a Singleton called Inventory whose job is to immediately save changes to the player’s inventory, such as when the player picks up some coins. Save data for my game uses the Godot SQLite plugin.

Initially I found that immediately saving to the database would cause a small chug in the game’s framerate each time, so I put the save code into a thread:

func update_inventory(new_item : Dictionary):
	var thread = Thread.new()
	thread.start(self,"_update_inventory_threaded",new_item,2)


func _update_inventory_threaded(new_item : Dictionary):    						
	Database.insert_data(new_item,Database.inventory_tbl_name)

However, this did not seem to remove the lag, and in fact this occasionally causes the game to hard crash (i.e. the game just closes).

Is there some other way to have instant saving without this lag? I want the player to be able to close the game at any time and still have all their progress saved.

:bust_in_silhouette: Reply From: timothybrentwood

You’re writing to disk in the middle of your game, disk access is one of the slowest things you can do on a computer, you’re gonna get frame drops if you do it while the game is running. You should probably create distinct points (e.g. auto-saves) at which you actually write the updated data to disk and just cache it in a variable otherwise.

:bust_in_silhouette: Reply From: omggomb

Have you tried using a single thread together with some sort of queue. If your Inventory changes often in a short amount of time you might be starting too many threads.

See here for an example: https://docs.godotengine.org/en/stable/tutorials/threads/using_multiple_threads.html#semaphores