Search code examples
androidc++multithreadingunity-game-engineopenmp

Unity reduces the number of available OpenMP threads


I use OpenMP in a shared android library. There is a sample method that just checks the number of CPUs and the max number of threads.

int maxThreads = omp_get_max_threads();
int numProcs = omp_get_num_procs();

When I call this method from a basic android application (AppCompatActivity), both values are set to 8 on the device with Qualcomm Snapdragon 855 CPU (8 cores).

maxThreads = 8;
numProc = 8;

When I try to call this method from a Unity application, the returned numbers of max threads and procs are 2.

maxThreads = 2;
numProc = 2;

Why the max threads number in the Unity application is less than in the basic app? Is there a way to increase the number of parallel threads that are actually used?


Solution

  • You don't say which OpenMP implementation you are using, which would certainly be useful to know.

    However, assuming that Android behaves like Linux at this level, then what is probably happening is that Unity is setting the process' affinity mask (see sched_{get,set}affinity(...), which reflects the logicalCPUs that the process should use. The OpenMP runtime almost certainly consults that to determine the number of threads it makes sense to create.

    On Linux a process can affinitize a thread to a logicalCPU which is outside its incoming affinity mask, but that is certainly bad behaviour, and may lead to poor performance, since, fundamentally, your process is at the bottom of the pile and should accept what it is told to do by higher level schedulers.

    To be sure you could write a function to print the affinity mask, then you can see what is happening. Alternatively the OpenMP implementation may have an envirable that will cause it to tell you what it's doing. (e.g. Try KMP_AFFINITY=verbose if using the Intel or LLVM runtime.)