c++ - 节能自旋环

标签 c++ c assembly x86 x86-64

我正在编写一个自旋循环来监视全局变量的变化。这有占用整个 CPU 核心的副作用,这很好,因为我使用的是多核机器。

我的问题是:它可以变得节能吗?我正在使用 C++,如果需要可以访问 x64 程序集。

这是我的代码:

void monitor_changes(int*variable_to_monitor){
    int last_value=*variable_to_monitor;
    while(1){ //this is the spin loop - don't want the os to interrupt it, but can it be energy efficient?
        int cur_value=*variable_to_monitor;
        if (*variable_to_monitor!=last_value){
            printf("value has changed!");
            last_value=cur_value;
        }
    }
}

编辑:我不想为此使用操作系统服务,因为监控需要尽快使用react。使用操作系统服务会导致延迟。

最佳答案

除非您有非常不寻常的用例,否则您的方法是错误的。您不应该使用自旋循环来监视对全局变量的更改。相反,您应该向观察者发出全局已更改的信号。如果使用 pthreads,请查看 pthread_cond_signalpthread_cond_wait。各种 C++ 库也有这些,例如 Boost 有互斥量和条件变量。一种老式的方法是使用管道,在显示器中选择管道,然后在更改全局时写入一个字符。

如果您确实需要监视全局,您可以考虑在检查之间休眠(您需要知道多长时间),考虑您的操作系统是否有导致计划发生的东西,或者考虑 pause 说明 - 参见: http://x86.renejeschke.de/html/file_module_x86_id_232.html

关于c++ - 节能自旋环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166153/

相关文章:

c++ - 为什么非常量静态变量需要在类外初始化?

使用 ASM 操作 Java 字节码

c - 当 main 什么都不返回时,为什么我得到了 linux c 中 main 调用的最后一个函数的返回值?

c - RSA 签名 : OpenSSL

c - 在汇编中解密二进制文件

assembly - NASM:如何正确访问 ssd 驱动器?

c++ - 使用 aligned_storage 时如何避免严格的别名错误

c++ - 使用 malloc C++ 时出现 C2440 错误

C++ 访问定义宏数据

c - 将新 worker 添加到列表中,但保持按名称排序