Setting thread processor affinity in Linux

If you want to set CPU affinity per QThread [doc.qt.nokia.com], Qt does not provide an API do this, and you will need to use native platform calls. Qt provides a native handle to the currently running thread via the static method QThread::currentThreadId() [qt.nokia.com].

In Linux you will want to take a look at pthread_setaffinity_np() (in /usr/include/pthread.h) which lets you set the affinity of a thread. The id returned by QThread::currentThreadId() is the same as pthread_self(), so to change the affinity of the current thread, you could do something like this:

cpu_set_t cpuset;

  1. CPU_ZERO(&cpuset);
  2. CPU_SET(cpuNumber, &cpuset);


  1. pthread_setaffinity((pthread_t) QThread::currentThreadId(), &cpuset);

You could just use pthread_self() as well, avoiding the cast.

No comments

Write a comment

Sorry, you must be logged in to post a comment.