How to Set Pthread CPU Affinity in Os X

Is it possible to set pthread CPU affinity in OS X?

Mac OS X has Thread Affinity API and you can use it with pthread ID as thread_policy_set(pthread_mach_thread_np(pthreadId), but, as far as I know, there are no APIs like sched_setaffinity.

How can I set a thread's CPU affinity in Qt5?

Usually that sort of things is done by extracting the native thread handle and then doing whatever system specific stuff necessary, as no accepted cross-platform API exists for low level thread management.

Indeed, if we inspect the source for the qthread_unix.cpp we will see the following:

Qt::HANDLE QThread::currentThreadId() Q_DECL_NOTHROW
{
// requires a C cast here otherwise we run into trouble on AIX
return to_HANDLE(pthread_self());
}

And in qthread_win.cpp the implementation will differ in the expected way:

Qt::HANDLE QThread::currentThreadId() Q_DECL_NOTHROW
{
return reinterpret_cast<Qt::HANDLE>(quintptr(GetCurrentThreadId()));
}

So, it is responsibility of the application code to do the proper low level actions pertaining to each platform it is expected to run on.

Python 3 on macOS: how to set process affinity

Not possible. See Thread Affinity API Release Notes:

OS X does not export interfaces that identify processors or control thread placement—explicit thread to processor binding is not supported. Instead, the kernel manages all thread placement. Applications expect that the scheduler will, under most circumstances, run its threads using a good processor placement with respect to cache affinity.

Note that thread affinity is something you'd consider fairly late when optimizing a program, there are a million things to do which have a larger impact on your program.

Also note that Python is particularly bad at multithreading to begin with.

How to set CPU affinity for a process from C or C++ in Linux?

You need to use sched_setaffinity(2).

For example, to run on CPUs 0 and 2 only:

#define _GNU_SOURCE
#include <sched.h>

cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(0, &mask);
CPU_SET(2, &mask);
int result = sched_setaffinity(0, sizeof(mask), &mask);

(0 for the first parameter means the current process, supply a PID if it's some other process you want to control).

See also sched_getcpu(3).



Related Topics



Leave a reply



Submit