How to hint the OS which blocks of memory should not be swapped to disk?

Viewed 108

When the system memory is being exhausted, OS begins to swap unused memory regions to disk. I'm wondering if a developer could control this process.

For example, I have 2 blocks of memory, both are not being used for some time. But I don't want the first block to be swapped to disk, because application is waiting for something, and this block should be processed as soon as possible. The other block is not that important, so it could be swapped to disk without a doubt.

There might be no cross-platform way, but maybe there are OS-specific (Windows, Linux, etc) ways or hacky tricks to prioritize swapping and "mark" certain blocks of memory that should be swapped last?

1 Answers

On POSIX systems, posix_madvise with the POSIX_MADV_WILLNEED flag provides this sort of advice. It's only advice, so it's up to the OS how it interprets it, but in my experience, it typically behaves as:

  1. Page in the memory range in bulk if it's currently paged out
  2. Don't page it out unless operating under severe memory pressure

mlock can be used to say "never swap", but it's no longer advice at that point; you've told the OS to never swap it out, even under severe memory pressure (if too many processes do this, you can trigger out of memory errors or broad performance degradation as less important memory is forced to stay resident at the expense of more important memory).

Related