Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you lock memory pages to physical RAM in boost (c++)?

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()).

like image 568
Chris Avatar asked Aug 21 '13 07:08

Chris


1 Answers

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.

like image 135
Mikhail Veltishchev Avatar answered Sep 27 '22 21:09

Mikhail Veltishchev