- Home /
Thread ending prematurely?
I'm developing a game that generates procedural terrain in 32x32 chunks. To prevent slight freezes in the game as the player moves around I'm trying to move the terrain calculations to their own thread. Once that threads completes, the main Unity thread takes over and generates the terrain mesh. The code works fine when everything runs in the main thread aside from the slight freezes. When I move the terrain generation code to it's own thread however, sometimes I'll get a complete 32x32 chunk created but most of the time I only get a small piece of the chunk created. Is there something about threading that I'm not taking into account here?
Update The problem was the method that was creating the thread was ending before the thread could complete. I added "while (thread.IsAlive) Thread.Sleep(1)" to the code and that solved the problem however it introduced the problem of having the main thread sleep which defeats the purpose of what I'm trying to do. Guess I'll have to try a different route.
Impossible to say without code. Threads don't just stop for no reason though.
I figured it out though I still don't have a solution. See my update. Thanks.
First, tell us what parts of multithreading that you are taking into account. Second, how are you creating threads, using a real thread or a co-routine? See the following similar question to see if it helps. http://answers.unity3d.com/questions/357033/unity3d-and-c-coroutines-vs-threading.html
Thanks supernat! Using a ThreadPool was exactly what I needed.
Answer by andrew-lukasik · Jun 21, 2017 at 02:30 PM
I had similar issue. It turned out that there was an exception but it wasn't printing to console due to not being main thread (throw-ing on worker thread manually will print nothing as well).
This is what helped - nesting your code inside try/catch block with Debug.LogException:
Thread thread = new Thread(
()=> {
try {
/*
Your actual code goes here
*/
} catch (System.Exception ex) {
Debug.LogException(ex);
}
}
);
Answer by FlaSh-G · Jun 21, 2017 at 03:31 PM
You can easily solve this problem: Don't wait with Thread.Sleep, but by waiting frame after frame:
void Update()
{
if(!workerThread.IsAlive)
{
DoAThing();
}
}
Or even better: Use a coroutine. Feel free to use this class of mine like this:
void Start()
{
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
yield return new CoroutineThread(() =>
{
// Threaded stuff here
});
// Stuff after thread has finished here
}