Skip to content

Instantly share code, notes, and snippets.

@jimcadden
Created September 11, 2015 15:50
Show Gist options
  • Save jimcadden/726eda693d6b0a42b916 to your computer and use it in GitHub Desktop.
Save jimcadden/726eda693d6b0a42b916 to your computer and use it in GitHub Desktop.
pthread round-robin affinity
static int current_cpu = -1;
int max_cpus = 8 * sizeof(cpu_set_t);
cpu_set_t m;
CPU_ZERO(&m);
sched_getaffinity(0, sizeof(cpu_set_t), &m);
for (int i = 0; i < max_cpus; ++i) {
int c = (current_cpu + i + 1) % max_cpus;
if (CPU_ISSET(c, &m)) {
CPU_ZERO(&m);
CPU_SET(c, &m);
int ret;
if ((ret = pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &m))) {
fprintf(stderr, "Can't set thread affinity: %s\n", strerror(ret));
exit(1);
}
current_cpu = c;
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment