Medium
Pinning a hot-loop thread with sched_setaffinity
A latency-sensitive hot-loop thread (e.g. polling a NIC ring buffer for market data) is left to run wherever the Linux scheduler happens to place it, and its tail latency is spiky. The team pins it to a single core with pthread_setaffinity_np()/sched_setaffinity() as shown below. Which of the following best explains why this reduces tail latency?
main.cpp
#include <sched.h>
#include <pthread.h>
#include <cstdio>
void pin_to_core(int core_id) {
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
if (rc != 0) {
perror("pthread_setaffinity_np");
}
}
int main() {
pin_to_core(2); // hot-loop thread confined to core 2
for (;;) {
// latency-sensitive work: e.g. poll a NIC ring buffer
}
}31 of 53 in Operating Systems