Debug.Log Breaks Threading

I’m having an odd bug pop up consistently where my code functions perfectly fine until I decide to toss in a Log. For instance I have some A* pathfinding running on a second thread that can be cancelled early if a new request arrives before the first was complete. This is done by setting a bool that the worker thread checks for each iteration and then waiting for the thread to join.

        if (threadState == State.Calculating)
        {
            endEarly = true;
            calcThread.Join();
            endEarly = false;
        }

This works perfectly but if I insert a debug statement at the beginning or end of this code block such as:
Debug.Log("Did not finish calculating before new request arrived.);The code will start failing spectacularly and enemies will fail to receive any pathfinding.
My question is why does this behaviour occur?

If you have an exception in the thread, Unity isn’t able to catch and display those in the console, so they just disappear into the ether. Whatever code you’ve added almost certainly is throwing an exception.

2 Likes

Maybe you have a race condition? It’s possible it’s not something about Debug.Log itself that causes the problem but just the extra time it takes to make that call causes the race condition to surface.

2 Likes

It’s acting exactly like a race condition issue which is why I’m so confused. If I’m calling Join() the main thread is waiting for the worker to finish so there should not be any possibility of a race condition as far as I’m aware.

I’ve heard Debug.Log is thread safe on the forum, but I haven’t seen that officially confirmed. So I’ve never trusted it. Debug.Log also is much slower than you might expect. When I do Debug.Log from a secondary thread I send the string to the main thread with a ConcurrentQueue and actually do the Debug.Log on the main thread. Not sure if that is actually necessary, but it has worked fine for me.

1 Like

Figured it out, tossed a try/catch in the thread and had it output the stacktrace on the next frame. Was just pure luck that it always worked without the Debug.Log statement. Cause was newly spawned enemies getting their grid based pathfinding calculated before they knew what part of the grid they were on throwing an IndexOutOfRange exception…

2 Likes