- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 Windows 机器上的三种环境中用 C++ 编写:
我正在处理庞大的数据集,基本上需要能够将它们分解成尽可能大的 block 以便在内存中进行操作。为了找到 block 的大小,我想象如下:
size_t findOptimalSize(long long beginningSize) {
long long currentSize = beginningSize;
while (currentSize > 0) {
try {
std::vector<double> v(currentSize);
return currentSize;
} catch (std::bad_alloc &ex) {
currentSize /= 10;
}
}
return 0;
}
int main() {
long long size(50000000000000);
try {
std::vector<double> v(size);
std::cout << "success" << std::endl;
} catch (std::bad_alloc &ex){
std::cout << "badAlloc" << std::endl;
}
size_t optimal = findOptimalSize(size);
std::cout << "optimal size: " + std::to_string(optimal);
return 0;
}
以上代码在 Windows 环境中的表现完全符合预期。然而,在这两个 Linux 环境中,虽然它总是能够抛出第一个 bad_alloc 异常,但它随后会执行以下两个操作之一:
new cannot satisfy memory request.This does not necessarily mean you have run out of virtual memory.It could be due to a stack violation caused by e.g. bad use of pointers or an out-of-date shared library
std::vector<double> v(currentSize);
行陷入了无限循环(我最好的猜测是,它接近 Linux 环境可用的内存量,并且卡住等待释放额外的一点额外内存以满足我的请求)有没有什么方法可以完成我正在尝试的事情并在 Linux 环境中回避这些问题?我猜容器会使事情复杂化,并使我简单的分配检查与它们复杂的内存管理逻辑混淆。
如何检查在这些情况下是否可以分配内存?
最佳答案
容器没有复杂的内存管理逻辑。您所看到的是一个名为 memory overcommit 的令人惊讶的 Linux 策略的结果。 .
在 Linux 中大分配不会失败; malloc()
总是成功。在您实际尝试使用内存之前,内存实际上并没有分配。如果操作系统不能满足需求,它会调用 OOM killer ,终止进程直到释放足够的内存。
为什么会这样?
A Linux computer typically has a lot of heterogeneous processes running in different stages of their lifetimes. Statistically, at any point in time, they do not collectively need a mapping for every virtual page they have been assigned (or will be assigned later in the program run).
A strictly non-overcommitting scheme would create a static mapping from virtual address pages to physical RAM page frames at the moment the virtual pages are allocated. This would result in a system that can run far fewer programs concurrently, because a lot of RAM page frames would be reserved for nothing.
( source )
您可能会觉得这很荒谬。你不会孤单。这是一个极具争议的系统。如果您最初的 react 是“这很愚蠢”,我鼓励您仔细阅读并暂停判断。最终,无论您是否喜欢过度使用,这是所有 Linux 开发人员都必须接受和应对的生活事实。
关于容器化 Linux 环境中的 C++ : why does attempting to allocate large vector causes SIGABRT or neverending loop instead of bad_alloc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71210491/
我有两个表: CREATE TABLE routing ( id integer NOT NULL, link_geom geometry, source integer, targ
我想使用 optaplanner 的“pin”功能进行固定操作。但是我得到“摆脱永无止境的选择器(过滤(FromSolutionEntitySelector(PersonAssignment)))以避
我在 Windows 机器上的三种环境中用 C++ 编写: 带有 Ubuntu 的 Docker Linux 容器 - g++ 编译器 (Ubuntu 9.3.0-17ubuntu1~20.04) 9
我已经红色了 optaplanner 文档,@PlanningPin 的用法非常简单。我的 PlanningEntity 是: @PlanningEntity() public class CrewG
我在 Windows 机器上的三种环境中用 C++ 编写: 带有 Ubuntu 的 Docker Linux 容器 - g++ 编译器 (Ubuntu 9.3.0-17ubuntu1~20.04) 9
我是一名优秀的程序员,十分优秀!