Skip to content

Instantly share code, notes, and snippets.

@yashshah1
Created April 20, 2020 12:49
Show Gist options
  • Save yashshah1/48734f9b7684c7c81b0192ea977f2726 to your computer and use it in GitHub Desktop.
Save yashshah1/48734f9b7684c7c81b0192ea977f2726 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include <stdio.h>
#include <math.h>
#include <sched.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
double waste_time(long n) {
double res = 0;
long i = 0;
while (i < n * 200000) {
i++;
res += sqrt(i);
}
return res;
}
int stick_this_thread_to_core(int core_id) {
int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
if (core_id < 0 || core_id >= num_cores)
return EINVAL;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
pthread_t current_thread = pthread_self();
return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);
}
int get_cpu_id_from_mask(cpu_set_t cpuset) {
int num_cores = sysconf(_SC_NPROCESSORS_ONLN), i;
for(i = 0; i < num_cores; ++i)
if(CPU_ISSET(i, &cpuset))
return i;
return -1;
}
void *thread_func(void *param) {
double result;
cpu_set_t cpuset;
int cpuid;
CPU_ZERO(&cpuset);
printf("Sticking thread to processor 0\n");
/* bind process to processor 0 */
if(stick_this_thread_to_core(0) != 0) {
perror("pthread_setaffinity_np");
}
/* waste some time so the work is visible with "top" */
result = waste_time(2000);
if(pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) != 0) {
perror("pthread_getaffinity_np");
}
cpuid = get_cpu_id_from_mask(cpuset);
if(cpuid == -1) {
perror("get_cpu_id_from_mask");
}
printf("result: %f, executed on core#: %d\n", result, cpuid);
printf("Sticking thread to processor 3\n");
/* bind process to processor 0 */
if(stick_this_thread_to_core(3) != 0) {
perror("pthread_setaffinity_np");
}
/* waste some time so the work is visible with "top" */
result = waste_time(2000);
CPU_ZERO(&cpuset);
if(pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset) != 0) {
perror("pthread_getaffinity_np");
}
cpuid = get_cpu_id_from_mask(cpuset);
if(cpuid == -1) {
perror("get_cpu_id_from_mask");
}
printf("result: %f, executed on core#: %d\n", result, cpuid);
}
int main(int argc, char *argv[]) {
pthread_t my_thread;
if (pthread_create(&my_thread, NULL, thread_func, NULL) != 0) {
perror("pthread_create");
}
pthread_exit(NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment