sched_getaffinity_threads.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* https://github.com/cirosantilli/linux-kernel-module-cheat#gdb-step-debug-multicore */
  2. #define _GNU_SOURCE
  3. #include <assert.h>
  4. #include <pthread.h>
  5. #include <sched.h>
  6. #include <stdbool.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. void* main_thread_0(void *arg) {
  11. int i;
  12. cpu_set_t mask;
  13. CPU_ZERO(&mask);
  14. CPU_SET(*((int*)arg), &mask);
  15. sched_setaffinity(0, sizeof(cpu_set_t), &mask);
  16. i = 0;
  17. while (true) {
  18. printf("0 %d\n", i);
  19. sleep(1);
  20. i++;
  21. }
  22. return NULL;
  23. }
  24. void* main_thread_1(void *arg) {
  25. int i;
  26. cpu_set_t mask;
  27. CPU_ZERO(&mask);
  28. CPU_SET(*((int*)arg), &mask);
  29. sched_setaffinity(1, sizeof(cpu_set_t), &mask);
  30. i = 0;
  31. while (true) {
  32. printf("1 %d\n", i);
  33. sleep(1);
  34. i++;
  35. }
  36. return NULL;
  37. }
  38. int main(void) {
  39. enum NUM_THREADS {NUM_THREADS = 2};
  40. pthread_t threads[NUM_THREADS];
  41. int thread_args[NUM_THREADS];
  42. pthread_create(&threads[0], NULL, main_thread_0, (void*)&thread_args[0]);
  43. pthread_create(&threads[1], NULL, main_thread_1, (void*)&thread_args[1]);
  44. pthread_join(threads[0], NULL);
  45. pthread_join(threads[1], NULL);
  46. return EXIT_SUCCESS;
  47. }