affinity.cc 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include "types.hh"
  2. #include "util.hh"
  3. #include "affinity.hh"
  4. #if HAVE_SCHED_H
  5. #include <sched.h>
  6. #endif
  7. namespace nix {
  8. #if HAVE_SCHED_SETAFFINITY
  9. static bool didSaveAffinity = false;
  10. static cpu_set_t savedAffinity;
  11. #endif
  12. void setAffinityTo(int cpu)
  13. {
  14. #if HAVE_SCHED_SETAFFINITY
  15. if (sched_getaffinity(0, sizeof(cpu_set_t), &savedAffinity) == -1) return;
  16. didSaveAffinity = true;
  17. printMsg(lvlDebug, format("locking this thread to CPU %1%") % cpu);
  18. cpu_set_t newAffinity;
  19. CPU_ZERO(&newAffinity);
  20. CPU_SET(cpu, &newAffinity);
  21. if (sched_setaffinity(0, sizeof(cpu_set_t), &newAffinity) == -1)
  22. printMsg(lvlError, format("failed to lock thread to CPU %1%") % cpu);
  23. #endif
  24. }
  25. int lockToCurrentCPU()
  26. {
  27. #if HAVE_SCHED_SETAFFINITY
  28. int cpu = sched_getcpu();
  29. if (cpu != -1) setAffinityTo(cpu);
  30. return cpu;
  31. #else
  32. return -1;
  33. #endif
  34. }
  35. void restoreAffinity()
  36. {
  37. #if HAVE_SCHED_SETAFFINITY
  38. if (!didSaveAffinity) return;
  39. if (sched_setaffinity(0, sizeof(cpu_set_t), &savedAffinity) == -1)
  40. printMsg(lvlError, "failed to restore affinity %1%");
  41. #endif
  42. }
  43. }