I'm trying to set the CPU affinity of threads on Linux. I'd like to know which one of the following approaches is recommended:
Get thread id using pthread_self()
Set CPU affinity using pthread_setaffinity_np(....) by passing the thread id as an argument
Get thread id using the gettid() call
Set CPU affinity using sched_setaffinity(....) by passing the thread id in the place of the process id
P.S: After setting the CPU affinity, I intend to increase the scheduling priority of the thread.
They are not the same. Here are some bits I collected from TLPI (I couldn't find a large-enough block that completely describes this). If you're in a hurry you probably want just the last part.
gettid
Linux 2.4 introduced a new system call, gettid()
, to allow a thread to obtain its own thread ID.
Each thread within a thread group is distinguished by a unique thread identifier. A thread ID is represented using the same data type that is used for a process ID, pid_t
. Thread IDs are unique system-wide, and the kernel guarantees that no thread ID will be the same as any process ID on the system, except when a thread is the thread group leader for a process.
pthread_self
Each thread within a process is uniquely identified by a thread ID. A thread can obtain its own ID using pthread_self()
.
The pthread_equal()
function is needed to compare thread ids because the pthread_t
data type must be treated as opaque data.
In the Linux threading implementations, thread IDs are unique across processes. However, this is not necessarily the case on other implementations, and SUSv3 explicitly notes that an application can’t portably use a thread ID to identify a thread in another process.
gettid
vs pthread_self
POSIX thread IDs are not the same as the thread IDs returned by the Linux-specific gettid()
system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid()
is a number (similar to a process ID) that is assigned by the kernel.
I would go with pthread_setaffinity_np
but be aware that the manual says:
These functions are implemented on top of the sched_setaffinity(2)