Proper use of threads with procedural generation (571743)

Hi everybody!
I have been working on a simple chunk based terrain generation system, with voxel octrees.
The overall method works pretty well, but testing this system with large amounts of chunks completely freezes the game/main thread until the generation process is finished.
Looking for a solution, I read about threads and coroutines and I implemented a simple thread class (based on this template) to call the “generate” function from it.
The only advantage I had was a faster generation, with full CPU usage, but the game still freezes until the chunks are completely loaded.
What am I doing wrong? Here some parts of the code:

public class ChunkThread : ThreadedJob {

    public Chunk chunk;

    protected override void ThreadFunction()
    {
        chunk.root = chunk.root.BuildOctree (chunk.pos, Chunk.size, -1);
    }

    protected override void OnFinished()
    {
        chunk.RenderChunk ();
    }
}

This is the simple Thread class I use to call the Build function, and the Render function when finished.
This piece of code below is the start\update method for every Chunk gameObject (I kept only the relevant part), that simply creates the Thread instance and calls Start() pressing the mouse button.

void Start () {
        t = new ChunkThread ();
        t.chunk = this;
    }
  
    void Update () {
        if (Input.GetButtonDown ("Fire1")) {
            t.Start ();
        }

I read about thread pools and asynchronous methods, but I don’t know if it coud be a solution, and most important I didn’t find any simple example on how these pools work in Unity.
Now, coming to the questions, what should I do to generate the terrain while still being able to play? Is there something wrong in my thread? Should I use a thread pool, if so how?
Thanks a lot!^^

1 Like

It’s hard to know exactly without seeing more. Tried a coroutine?

I will post the chunk class later (answering from a different place), but talking about how it works, basically:

  • A “world” gameObject instantiates in a grid the Chunk prefabs
  • Every chunk has the previous chunk script, with a thread assigned.

No, I didnt try coroutines mainly because I read they still run on the main thread, and I wanted to use more than a single thread for the generation, to speed it up.

However, I should give it a try! Maybe is it possible to “thread” a coroutine? :stuck_out_tongue:
Reading articles, it seems like the final solution should be using a threadpool, but I could be wrong.