I'm messing with shared memory objects in boost, for a real-time C++ application that needs to lock the memory page(s) into physical memory. I'm not seeing a way to do this in boost. I feel like I'm missing something because I know both Windows and Linux have a way of doing this (mlock()
and VirtualLock()
).
Asked
Active
Viewed 992 times
6

IndustProg
- 627
- 1
- 13
- 33

Chris
- 613
- 6
- 7
-
If it's a real-time app and touching those pages in real-time, they won't page out anyway. Sounds like premature optimization. – MSalters Aug 21 '13 at 07:15
-
9In a real-time app, you shouldn't just hope that the OS does the right thing. He is absolutely correct in wanting to lock the pages down. – StilesCrisis Aug 21 '13 at 07:21
-
2Boost just doesn't have such a library. – Igor R. Aug 21 '13 at 09:40
-
ok, thank you for the sanity check – Chris Aug 22 '13 at 23:59
-
1I have made grep of `mlock` and `VirtualLock` in Boost sources - does not find anything. – Evgeny Panasyuk Oct 28 '13 at 14:06
1 Answers
4
As of my experience, it's better to write a tiny cross-platform library that provides necessary functionality for this. Internally there will be some #ifdef-s, of course.
Something like this (assuming GetPageSize
and Align*
already implemented):
void LockMemory(void* addr, size_t len) {
#if defined(_unix_)
const size_t pageSize = GetPageSize();
if (mlock(AlignDown(addr, pageSize), AlignUp(len, pageSize)))
throw std::exception(LastSystemErrorText());
#elif defined(_win_)
HANDLE hndl = GetCurrentProcess();
size_t min, max;
if (!GetProcessWorkingSetSize(hndl, &min, &max))
throw std::exception(LastSystemErrorText());
if (!SetProcessWorkingSetSize(hndl, min + len, max + len))
throw std::exception(LastSystemErrorText());
if (!VirtualLock(addr, len))
throw std::exception(LastSystemErrorText());
#endif
}
We also tried to use some of boost:: libraries, but were tired to fix cross-platform issues and switched to our own implementations. It's slower to write, but it works.

Mikhail Veltishchev
- 59
- 8