1 /* 2 * Copyright 2023, Jérôme Duval, jerome.duval@gmail.com. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 6 7 #include <pthread.h> 8 #include <sched.h> 9 #include <stdio.h> 10 #include <stdlib.h> 11 12 13 int 14 main(int argc, char** argv) 15 { 16 if (argc != 2) 17 exit(1); 18 if (strcmp(argv[1], "off") != 0) { 19 printf("with affinity on CPU 1\n"); 20 pthread_t thread = pthread_self(); 21 cpuset_t cpuset; 22 CPUSET_ZERO(&cpuset); 23 CPUSET_SET(1, &cpuset); 24 if (pthread_setaffinity_np(thread, sizeof(cpuset_t), &cpuset) != 0) { 25 fprintf(stderr, "pthread_setaffinity_np failed\n"); 26 exit(1); 27 } 28 if (pthread_getaffinity_np(thread, sizeof(cpuset_t), &cpuset) != 0) { 29 fprintf(stderr, "pthread_getaffinity_np failed\n"); 30 exit(1); 31 } 32 if (!CPUSET_ISSET(1, &cpuset)) 33 fprintf(stderr, "affinity not on CPU 1\n"); 34 if (sched_getcpu() != 1) 35 fprintf(stderr, "not running on CPU 1\n"); 36 } else { 37 printf("without affinity\n"); 38 } 39 int* p; 40 while (true) 41 (*p)++; 42 return *p; 43 } 44