Can custom c++ plugin do multiprocessing (threading) for Unity ?

For example, I have while(true){} loop in some function e.g. grasping frame from camera.

Can i create a thread for this function ? so it won’t interrupt Unity’s processes.
Also, i have huge computations which i want to do it in threads.

Can i use some c++ library like Openmpi to implement this ?

thx u very much and sry for my poor grammar.

Just as a word of warning, I tried threading a ‘while true’ loop using both a dedicated thread and a threadpool. Although the game would play once, it would crash when I tried to play again, or when i tried to exit Unity.

I think this had something to do with unity failing to abort the thread when the game stops but I’m not sure.

If you want to use some OpenMPI code it’s quite easy to define external functions in C# scripts using System.Runtime.InteropServices, just make sure that if you’re using a dll you define the correct Calling Convention!

If you want more info on threading, here’s a video I made:

As a rule of thumb, Unity’s API is off-limits to any other threads than the mainthread. There are few notable exceptions, such as using functions in Mathf or calling Debug.Log. But everything that has to do with the renderstate, such as changing the values in a transform, will throw exceptions if you access it from a separate thread. It doesn’t matter if the separate thread is instantiated by a plugin or whatever.

If you have heavy computations, you can still multithread it (also in plugins), but you have to think of some clever way to make the required data available to it without requiring the thread to access Unity stuff. Maybe you can save the data first in some datastructure that you know to be threadsafe, like a list of objects or something, and then start the thread and have it chew through that list?