使电话机会化 [英] Make calloc opportunistic

查看:73
本文介绍了使电话机会化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在linux上, malloc 的行为是机会性的,只有在首次访问虚拟内存时才通过实际内存来支持它.

On linux malloc behaves opportunistically, only backing virtual memory by real memory when it is first accessed. Would it be possible to modify calloc so that it also behaves this way (allocating and zeroing pages when they are first accessed)?

推荐答案

它不是 malloc()的功能,使其具有机会性".这是内核的一个功能, malloc()与它无关.

It is not a feature of malloc() that makes it "opportunistic". It's a feature of the kernel with which malloc() has nothing to do whatsoever.

malloc()每当需要更多内存来满足请求时就向内核请求一小部分内存,而内核则说是的,当然,您拥有它".每次都没有实际提供内存.内核还通过提供零存储页面来处理后续的页面错误.请注意,出于安全考虑,内核提供的所有内存都将被清零,因此它同样适用于 malloc() calloc().

malloc() asks the kernel for a slap of memory everytime it needs more memory to fulfill a request, and it's the kernel that says "Yeah, sure, you have it" everytime without actually supplying memory. It is also the kernel that handles the subsequent page faults by supplying zero'ed memory pages. Note that any memory that the kernel supplies will already be zero'ed out due to safety considerations, so it is equally well suited for malloc() and for calloc().

也就是说,除非 calloc()实现通过无条件将页面本身清零(产生提示内核实际提供内存的页面错误)来破坏此效果,否则它将具有相同的机会的"行为为 malloc().

That is, unless the calloc() implementation spoils this by unconditionally zeroing out the pages itself (generating the page faults that prompt the kernel to actually supply memory), it will have the same "opportunistic" behavior as malloc().

在我的系统上,以下程序在只有2 GiB内存的系统上成功分配了1 TiB(!):

On my system, the following program successfully allocates 1 TiB (!) on a system with only 2 GiB of memory:

#include <stdlib.h>
#include <stdio.h>

int main() {
    size_t allocationCount = 1024, successfullAllocations = 0;
    char* allocations[allocationCount];
    for(int i = allocationCount; i--; ) {
        if((allocations[i] = calloc(1, 1024*1024*1024))) successfullAllocations++;
    }
    if(successfullAllocations == allocationCount) {
        printf("all %zd allocations were successfull\n", successfullAllocations);
    } else {
        printf("there were %zd failed allocations\n", allocationCount - successfullAllocations);
    }
}

我认为,可以肯定地说,至少我盒子上的 calloc()实现的表现是机会主义的".

I think, its safe to say that at least the calloc() implementation on my box behaves "opportunistically".

这篇关于使电话机会化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆