首页 > 解决方案 > 我可以将一个值加载到寄存器中而不会停止,直到它从内存中获取?

问题描述

我想启动主内存访问,但只要我在某个时候获得新值,我就不会太在意新值何时到达。同时,我想继续使用当前在寄存器中的值,而不是在内存获取完成之前停止。

这是 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;
    }
}

标签: cassemblyvolatilecpu-registers

解决方案


推荐阅读