Can I limit a thread's CPU usage?

Godot Version

4.2.1

Question

I’m wondering if I can limit a thread’s CPU usage.

I’m doing a procudural generated terrian. I need to generate heightmap, splatmap and some other maps for the terrain. Originally I did this completely in _ready phrase, but it will cost a lot of time. A map size around 10241024 will cost less than one minute, which is acceptable. But my target is size around 81928192, so it will contain enough space for my game, but this cost a huge amount of time (10-20minutes). So I want to do terrain generation while the game is running.

These is my game’s screenshots.

I used a thread like this

var semaphore: Semaphore
var thread : Thread
func _ready():
  semaphore = Semaphore.new()
  thread = Thread.new()
  thread.start(_world_streaming,Thread.PRIORITY_LOW)
func _world_streaming():
  Thread.set_thread_safety_checks_enabled(false)
  while true:
    semaphore.wait()
    _caculate_world()

In the _caculate_world method, it will caculate world maps of certain area and update the terrain. I used a timer which will call semaphore to post when it get timeout signal. This actually works, it caculates and updates the terrain while the game is running. But this has a huge problem.I expected it to run parrallel to my game while not causing framerate drop.

I originally thought the thread will only use one core of my CPU, but it consumed all my CPU resource and caused dramatic framerate drop (from 200 fps to 20 fps) in my game.

So I’m wondering is it possible to limit cpu usage for a certain thread? Or are there any other method to do this?

You should only have one thread. it could be that you are _calculating_world many segments and the thread is sleeping and waking up many times being scheduled on different CPU cores each time. and as you said calculate_world needs a lot of resources.

but to answer your question no. at least not easily, and not through Godot.

I would suggest profiling your loading code and try and find ways to optimize it. also how does the thread return the resources? does it block anywhere on the main thread?