c - 我可以将一个值加载到寄存器中而不会停止,直到它从内存中获取?
问题描述
我想启动主内存访问,但只要我在某个时候获得新值,我就不会太在意新值何时到达。同时,我想继续使用当前在寄存器中的值,而不是在内存获取完成之前停止。
这是 C 语言中的一个激励性玩具示例。我有一个工作循环,它不断地做一些工作,并将结果累积到一些存储中。每隔一段时间,我想交换值的累积位置(类似于 Linux 服务器上的日志轮换)。只要每个计算值都累积到一个存储位置,我就很高兴。
正如所写,在内存提取发生时,cpu 将停止,因为我没有表示我想使用寄存器中预先存在的“错误/陈旧”值,直到内存提取完成。
如何让编译器/cpu 清楚这一点?如果需要直接写汇编就好了。我对适用于任何/所有架构的答案感兴趣。
// does unspecified work and returns an int.
inline int do_work();
// where our main thread accumulates its work
int * accumulator;
// assume that some other thread is concurrently updating this.
// Every so often, we want to switch our accumulator to be a
// newer value taken from here, but we're not fussy about exactly
// when that switch happens.
int * volatile * current_accumulator;
void work_loop() {
int * accumulator = *current_accumulator;
// Here, I want to block once until `*current_accumulator`
// is loaded into a register.
while (1) {
for (int i = 0; i < 100; ++i) {
// This has a dependency on the memory load, and so
// it will stall until the new value is loaded into
// the register. However I don't want that. I want the
// register to update eventually, but I want to always
// be using the value that happens to currently be there.
*accumulator += do_work();
}
accumulator = *current_accumulator;
}
}
解决方案
推荐阅读
- c# - 如何通过引号和逗号开头或结尾的引号进行解析?
- c++ - “ActivationsSource”不是类或命名空间名称
- excel - 在列中的数据更改后插入空白行
- mysql - 更改列值取决于出现次数
- python - 使用 Google Compute Engine 默认服务帐号签署 Google Cloud Storage URL
- c# - Unity 网络管理器不会在网络起始位置生成对象
- go - 对 gqlgen GraphQL API 的 curl POST 请求的正确形状是什么?
- swift - 在 Swift 中过滤 ManagedObject FetchResults 数组
- python - 如何在字典python列表中设置默认值?
- python - python,如何在范围循环中跳过行