Skip to content

Instantly share code, notes, and snippets.

@mbs0221
Last active November 23, 2023 15:25
Show Gist options
  • Save mbs0221/060d7fd2b1478ace7dffdb38fceeb60a to your computer and use it in GitHub Desktop.
Save mbs0221/060d7fd2b1478ace7dffdb38fceeb60a to your computer and use it in GitHub Desktop.
cpuset
// This is a simple program to demonstrate the use of the cpuset
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>
#include <sys/types.h>
#include <sys/syscall.h>
#define NUM_THREADS 2
void *thread_func(void *arg)
{
int i;
int cpu;
cpu_set_t cpuset;
cpu = sched_getcpu();
printf("Thread %d running on CPU %d\n", (int)arg, cpu);
CPU_ZERO(&cpuset);
CPU_SET(cpu, &cpuset);
if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset) == -1) {
perror("sched_setaffinity");
exit(1);
}
for (i = 0; i < 100000000; i++)
;
return NULL;
}
int main(int argc, char *argv[])
{
int i;
pthread_t tid[NUM_THREADS];
for (i = 0; i < NUM_THREADS; i++) {
if (pthread_create(&tid[i], NULL, thread_func, (void *)i) != 0) {
perror("pthread_create");
exit(1);
}
}
for (i = 0; i < NUM_THREADS; i++) {
if (pthread_join(tid[i], NULL) != 0) {
perror("pthread_join");
exit(1);
}
}
return 0;
}
#!/bin/bash

# Set CPU affinity for process
taskset -c 0,1,2,3 ./my_program
// Set CPU affinity for thread
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);

// Set CPU affinity for process using percpu variable
cpumask_t mask;
cpumask_clear(&mask);
cpumask_set_cpu(0, &mask);
cpumask_set_cpu(1, &mask);
cpumask_set_cpu(2, &mask);
cpumask_set_cpu(3, &mask);
set_cpus_allowed_ptr(current, &mask);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment