我正在编写一个自旋循环来监视全局变量的变化。这有占用整个 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_signal
和 pthread_cond_wait
。各种 C++ 库也有这些,例如 Boost 有互斥量和条件变量。一种老式的方法是使用管道,在显示器中选择管道,然后在更改全局时写入一个字符。
如果您确实需要监视全局,您可以考虑在检查之间休眠(您需要知道多长时间),考虑您的操作系统是否有导致计划发生的东西,或者考虑 pause
说明 - 参见:
http://x86.renejeschke.de/html/file_module_x86_id_232.html
关于c++ - 节能自旋环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21166153/