Make DontSwapMemoryRAII work on windows

This commit is contained in:
Sebastian Messmer 2018-05-16 21:48:27 -07:00
parent bd1dc9f747
commit 3ccb46c537
4 changed files with 63 additions and 3 deletions

View File

@ -42,7 +42,8 @@ set(SOURCES
assert/AssertFailed.cpp
system/get_total_memory.cpp
system/homedir.cpp
system/memory.cpp
system/memory_nonwindows.cpp
system/memory_windows.cpp
)
add_library(${PROJECT_NAME} STATIC ${SOURCES})

View File

@ -10,11 +10,11 @@ namespace cpputils {
// i.e. tells the operating system not to swap it.
class DontSwapMemoryRAII final {
public:
DontSwapMemoryRAII(const void* addr, size_t len);
DontSwapMemoryRAII(void* addr, size_t len);
~DontSwapMemoryRAII();
private:
const void* addr_;
void* const addr_;
const size_t len_;
};

View File

@ -0,0 +1,30 @@
#if !defined(_MSC_VER)
#include "memory.h"
#include <sys/mman.h>
#include <errno.h>
#include <stdexcept>
#include <cpp-utils/logging/logging.h>
using namespace cpputils::logging;
namespace cpputils {
DontSwapMemoryRAII::DontSwapMemoryRAII(void *addr, size_t len)
: addr_(addr), len_(len) {
const int result = ::mlock(addr_, len_);
if (0 != result) {
throw std::runtime_error("Error calling mlock. Errno: " + std::to_string(errno));
}
}
DontSwapMemoryRAII::~DontSwapMemoryRAII() {
const int result = ::munlock(addr_, len_);
if (0 != result) {
LOG(WARN, "Error calling munlock. Errno: {}", errno);
}
}
}
#endif

View File

@ -0,0 +1,29 @@
#if defined(_MSC_VER)
#include "memory.h"
#include <Windows.h>
#include <stdexcept>
#include <cpp-utils/logging/logging.h>
using namespace cpputils::logging;
namespace cpputils {
DontSwapMemoryRAII::DontSwapMemoryRAII(void *addr, size_t len)
: addr_(addr), len_(len) {
const BOOL result = ::VirtualLock(addr_, len_);
if (!result) {
throw std::runtime_error("Error calling VirtualLock. Errno: " + std::to_string(GetLastError()));
}
}
DontSwapMemoryRAII::~DontSwapMemoryRAII() {
const BOOL result = ::VirtualUnlock(addr_, len_);
if (!result) {
LOG(WARN, "Error calling VirtualUnlock. Errno: {}", GetLastError());
}
}
}
#endif