Medium
mlockall() after pre-faulting a buffer
A real-time audio callback (equally: an HFT market-data hot path) must never miss its deadline, and the team is worried the kernel could reclaim/swap a page of its scratch buffer under memory pressure, later stalling the callback on a page fault mid-deadline. The code below touches the buffer once via memset(), then calls mlockall(MCL_CURRENT | MCL_FUTURE) before ever entering the real-time loop. Why does this combination guarantee later accesses to hot_buffer inside the real-time loop will never stall on a page fault (not even a fast minor one) for the rest of the process's lifetime?
main.cpp
#include <sys/mman.h>
#include <cstring>
#include <cstdio>
int main() {
char* hot_buffer = new char[1 << 20]; // 1MB scratch buffer for the RT path
memset(hot_buffer, 0, 1 << 20); // first touch: pages become resident here
// Lock every page currently mapped into this process (including hot_buffer),
// and keep any pages mapped in the future locked too.
if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
perror("mlockall");
return 1;
}
// ... enter real-time audio callback / market-data hot loop, using hot_buffer ...
}35 of 53 in Operating Systems