如何在boost(c ++)中将内存页锁定到物理RAM?

Chr*_*ris 5 c++ boost shared-memory boost-thread

我在使用boost中的共享内存对象,因为需要将内存页锁定到物理内存中的实时C++应用程序.在增强中我没有看到这样做的方法.我觉得我错过了一些东西,因为我知道Windows和Linux都有办法做到这一点(mlock()VirtualLock()).

Mik*_*hev 4

根据我的经验,最好编写一个小型跨平台库来为此提供必要的功能。当然,内部会有一些#ifdef-s。

像这样的东西(假设GetPageSize并且Align*已经实现):

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
}
Run Code Online (Sandbox Code Playgroud)

我们还尝试使用一些 boost:: 库,但厌倦了解决跨平台问题并切换到我们自己的实现。写起来比较慢,但是可以用。