Search code examples
multithreadingqtqthread

QThread::idealThreadCount() always returning "2"


I need to display, in a QSpinBox, the number of cores, or threads, that the CPU has. The problem is:

QThread cpuInfo(this); //get CPU info
ui->spnBx_nmb_nodes->setValue(cpuInfo.idealThreadCount()); //get thread count

This is always returning "2". I tried in a "2 cores/4 threads" notebook; a "4 cores/8 threads" computer and a "12 cores/ 24 threads" server. In all the cases, this is returning "2" as the ideal thread count.

Can someone, please, give me some light?


Solution

  • idealThreadCount()'s implementation is different on different OS's:

    On Windows, QThread::idealThreadCount() calls the Win32 function GetNativeSystemInfo() and from its results, returns the dwNumberOfProcessors value from the SYSTEM_INFO struct that call populates.

    On Linux (and most other Unix-y OS)'s, QThread::idealThreadCount() calls sysconf(_SC_NPROCESSORS_ONLN) and returns that value.

    On MacOS/X (and BSD and iOS), QThread::idealThreadCount() calls sysctl(CTL_HW, HW_NCPU) and returns the value it receives from there.

    QThread::idealThreadCount() also contains some other back-end implementations for less-commonly used OS's, which I won't attempt to summarize here; if you need to look for yourself, the code is at lines 461-515 of qtbase/src/corelib/thread/qthread_unix.cpp.

    Given all of the above, the question devolves to, why is the OS-command (that Qt is calling through to) returning 2 instead of a more appropriate number? It sounds like a bug to me, although one other possibility is that idealThreadCount() is returning the correct number, but your QSpinBox is clamping that number down to 2 for some reason. If you haven't done so already, I suggest printing out the value returned by cpuInfo.idealThreadCount() directly, in addition to passing it to setValue(), just to be sure.