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()
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With