| 1 |
dimitri |
1.1 |
/* |
| 2 |
|
|
** Pin the calling process to a cpu |
| 3 |
|
|
*/ |
| 4 |
|
|
|
| 5 |
|
|
#include <stdio.h> |
| 6 |
|
|
#include <ctype.h> |
| 7 |
|
|
#include <unistd.h> |
| 8 |
|
|
#include <stdlib.h> |
| 9 |
|
|
|
| 10 |
|
|
#define __USE_GNU 1 |
| 11 |
|
|
#include <sched.h> |
| 12 |
|
|
|
| 13 |
|
|
|
| 14 |
|
|
#define DIE_IF(expr) { if (expr) {perror( # expr ) ; exit(1);} } |
| 15 |
|
|
|
| 16 |
|
|
|
| 17 |
|
|
/* Pin to the cpu */ |
| 18 |
|
|
int |
| 19 |
|
|
pin_absolute(int cpu) |
| 20 |
|
|
{ |
| 21 |
|
|
cpu_set_t new_affinity; |
| 22 |
|
|
if ((cpu < 0) || (cpu >= CPU_SETSIZE)) return -1; |
| 23 |
|
|
|
| 24 |
|
|
/* Set a new affinity mask with just the one cpu */ |
| 25 |
|
|
CPU_ZERO(&new_affinity); |
| 26 |
|
|
CPU_SET(cpu, &new_affinity); |
| 27 |
|
|
DIE_IF(sched_setaffinity(0, sizeof(cpu_set_t), &new_affinity) < 0); |
| 28 |
|
|
return 0; |
| 29 |
|
|
} |
| 30 |
|
|
|
| 31 |
|
|
|
| 32 |
|
|
/* Pin to the cpu, relative to the current affinity mask */ |
| 33 |
|
|
int |
| 34 |
|
|
pin_relative(int relative_cpu) |
| 35 |
|
|
{ |
| 36 |
|
|
int count, i; |
| 37 |
|
|
cpu_set_t current_affinity, new_affinity; |
| 38 |
|
|
if ((relative_cpu < 0) || (relative_cpu >= CPU_SETSIZE)) return -1; |
| 39 |
|
|
|
| 40 |
|
|
/* Get the current cpu affinity */ |
| 41 |
|
|
CPU_ZERO(¤t_affinity); |
| 42 |
|
|
DIE_IF(sched_getaffinity(0, sizeof(cpu_set_t), ¤t_affinity) < 0); |
| 43 |
|
|
|
| 44 |
|
|
/* Find the cpu'th set bit */ |
| 45 |
|
|
for(count = -1, i = 0; i < CPU_SETSIZE; i++) { |
| 46 |
|
|
if (CPU_ISSET(i, ¤t_affinity)) { |
| 47 |
|
|
if (++count == relative_cpu) break; |
| 48 |
|
|
} |
| 49 |
|
|
} |
| 50 |
|
|
|
| 51 |
|
|
/* Check the current affinity mask had enough bits to satisfy the request */ |
| 52 |
|
|
if (count < relative_cpu) return -1; |
| 53 |
|
|
|
| 54 |
|
|
|
| 55 |
|
|
/* Set a new affinity mask with just the one cpu */ |
| 56 |
|
|
CPU_ZERO(&new_affinity); |
| 57 |
|
|
CPU_SET(i, &new_affinity); |
| 58 |
|
|
DIE_IF(sched_setaffinity(0, sizeof(cpu_set_t), &new_affinity) < 0); |
| 59 |
|
|
return 0; |
| 60 |
|
|
} |
| 61 |
|
|
|
| 62 |
|
|
|
| 63 |
|
|
|
| 64 |
|
|
/* Fortran interface */ |
| 65 |
|
|
int pin_absolute_(int *cpu) { return pin_absolute(*cpu); } |
| 66 |
|
|
int pin_relative_(int *relative_cpu) { return pin_relative(*relative_cpu); } |
| 67 |
|
|
|