我目前正在研究一次加载和转换多个图像的管道。由于许多图像同时发生这种情况(1440),因此内存占用非常大。因此,我尝试实现基于 setrlimit 的内存管理系统,但是它似乎不会影响生成的线程(std::thread),因为它们会很高兴地忽略限制 - 我知道这是因为在线程函数 - 并最终导致我的程序被杀死。这是我用于设置限制的代码:
void setMemoryLimit(std::uint64_t bytes)
{
struct rlimit limit;
getrlimit(RLIMIT_AS, &limit);
if(bytes <= limit.rlim_max)
{
limit.rlim_cur = bytes;
std::cout << "New memory limit: " << limit.rlim_cur << " bytes" << std::endl;
}
else
{
limit.rlim_cur = limit.rlim_max;
std::cout << "WARNING: Memory limit couldn't be set to " << bytes << " bytes" << std::endl;
std::cout << "New memory limit: " << limit.rlim_cur << " bytes" << std::endl;
}
if(setrlimit(RLIMIT_AS, &limit) != 0)
std::perror("WARNING: memory limit couldn't be set:");
// included for debugging purposes
struct rlimit tmp;
getrlimit(RLIMIT_AS, &tmp);
std::cout << "Tmp limit: " << tmp.rlim_cur << " bytes" << std::endl; // prints the correct limit
}
我正在使用 Linux。手册页指出 setrlimit 会影响整个过程,所以我有点不知道为什么线程似乎没有受到影响。
编辑:顺便说一下,上面的函数是在 main() 的最开始调用的。