Pthread Affinity

The following example shows how to bind a pthread to a particular core or distribute multiple threads evenly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#define _GNU_SOURCE

#include <pthread.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>

void *f()
{

while(true) ;
}

void bind_to_core_3()
{

cpu_set_t cpuset;
pthread_t child;
pthread_create(&child, NULL, f, NULL);

CPU_ZERO(&cpuset);
CPU_SET(3, &cpuset);

pthread_setaffinity_np(child, sizeof(cpu_set_t), &cpuset);
}

void distribute_balancely(uint32_t n_threads)
{

cpu_set_t cpuset, basecpuset;
assert(n_threads <= 64);
static pthread_t threads[64];
for (uint32_t i = 0; i < n_threads; i++) {
int ret = pthread_create(&threads[i], NULL, f, NULL);
assert(ret == 0);
for (int j = 0; j < CPU_SETSIZE; ++j) {
if (CPU_ISSET(j, &basecpuset)) {
CPU_ZERO(&cpuset);
CPU_SET(j, &cpuset);
CPU_CLR(j, &basecpuset);
break;
}
}
if (CPU_COUNT(&basecpuset) == 0) {
ret = pthread_getaffinity_np(
threads[i], sizeof(cpu_set_t), &basecpuset);
assert(ret == 0);
}
ret = pthread_setaffinity_np(
threads[i], sizeof(cpu_set_t), &cpuset);
assert(ret == 0);
}
}

int main(int argc, char *argv[])
{

pthread_exit(0);
}