How to save some resource in another thread and use same thread

Godot Version

4.4.1

Question

I want to save a custom resource class everytime an action happens. It is a statistics file so i dont wan’t to occupy main thread for this. My problem is i can save in another thread but i need to create a thread everytime an action happens. I don’t want that(creating new thread) since they are expensive so i want to use only one additional worker thread continously and keep it alive, how to achieve that? My StatisticsManager is an autoload/singleton class and i am doing threaded operations in this class.

var thread:Thread = Thread.new()
var mutex:Mutex = Mutex.new()

func update_statistics_for_level_played() -> Statistics:
	statistics.total_level_played_count += 1
	thread.start(save_statistics)
	return statistics


func save_statistics(reinitialize:bool = true) -> void:
	mutex.lock()
	ResourceSaver.save(statistics, Constants.STATISTICS_FULL_PATH)
	mutex.unlock()
	#if reinitialize:
        #thread.wait_to_finish() <-- can't do that either
		#thread = Thread.new() <--- dont want that

I also need to make sure that save_statistics can not be called before it finishes^^

You may be able to use a semaphore?

var thread:Thread = Thread.new()
var semaphore := Semaphore.new()

func _ready() -> void:
	thread.start(save_statistics)
	# semaphore.post() to run `save_statistics` once on another thread


func save_statistics() -> void:
	while true: # replace with a bool so this can end
		semaphore.wait()
		ResourceSaver.save(statistics, Constants.STATISTICS_FULL_PATH)
1 Like

You could also use threads provided by WorkerThreadPool: WorkerThreadPool — Godot Engine (stable) documentation in English

1 Like

Thanks it worked