Can I use Unity math function in other threads?

I've read that Unity is not thread safe and I can only call Unity API in main thread. I'm trying to use multi-threading mainly for pure math calculation such as vector manipulation or something like that. I want to ask that can I use Unity basic math function in other thread such as vector magnitude, square root, dot/cross product etc? Or do I need to code those calculation functions too?

As far as I have heard, the official line is that the whole Unity API is not thread safe. Whether this applies to particular aspects such as the Mathf class, I'm not sure.

Personally, I can't see how a static math function which uses only variables defined within its own scope could be thread-unsafe, but that's just speculation without access to the actual source code.

However, since version 2.6, Unity has an assert which checks whether the the non-thread-safe functions are being called from an external thread. So, if you're doing something unsafe, you should get an assert fail in the console, looking something like this:


If you're not getting that message, you may be safe.

If you are getting the warning, you might want to implement your own thread-safe versions of those particular functions (which are relatively simple, and many examples exist out there which you could copy).

Incidentally, Debug.Log is thread safe (I think this is the only Unity function where this has been specified). So you can still log results from your functions which are running in other threads!

System.Math is for sure thread-safe, though it doesn't have vector functions.

There isn't any reason for me to believe that the Mathf function isn't thread-safe.

Did you try it? Something like this would be really easy to test, so why not just try it and see if it works instead of asking here? A better question to ask here is what alternatives you could use if it doesn't work.

Yes you can. What you can't (or shouldn't) do is manipulating the renderstate from a thread, as this probably will crash unity.