Setting tasks CPU affinity

Gilad Ben-Yossef May 15th, 2008

Linux kernel 2.6 and latest versions of 2.4 support two system calls that allow one to limit processes to specific CPUs.

The system calls are:

#include <sched.h>
 
int sched_setaffinity(pid_t  pid, unsigned int len, unsigned long *mask);
 
int sched_getaffinity(pid_t pid, unsigned int len, unsigned long *mask);

pid is the process id of the process to assign to certain CPUs. Use ‘0′ here to denote the current process.

len is the length of the CPU bit mask, and mask is a pointer to a bit mask denoting which CPU can the process run on.

For a good discussion and a code example, look here:

http://www-128.ibm.com/developerworks/linux/library/l-affinity.html

This post originally appeared in the Codefidence Technoblog

Using proccess specific APIs on threads

Gilad Ben-Yossef May 15th, 2008

A lot of POSIX API’s require a PID, or process ID, as a parameter. Sometime it is useful to use such an API on a thread, rather then a process.

Since Linux internally implements all processes and threads as tasks, one can use the Linux specific gettid(2) system call to get the “Thread ID” of a thread, which is really equal to a process PID, at least so much as to be useful as a parameter for a POSIX system call that requires a PID.

The use is Linux specific, non portable and it is not clear if it is a stable API or an undocumented coincidence. Use with care.

This post originally appeared in the Codefidence Technoblog