考虑一个简单的(在我的情况下是全局)变量:
int i;
Run Code Online (Sandbox Code Playgroud)
在某处访问此变量
pthread_mutex_lock(i_mutex);
if(i == other value) {
do_something();
}
pthread_mutex_unlock(i_mutex);
Run Code Online (Sandbox Code Playgroud)
另一个线程i 在保持时更新i_mutex.编译器可以缓存值,i所以我没有得到最近的值?一定i是不稳定的?
如果我有一些看起来像这样的代码:
typedef struct {
bool some_flag;
pthread_cond_t c;
pthread_mutex_t m;
} foo_t;
// I assume the mutex has already been locked, and will be unlocked
// some time after this function returns. For clarity. Definitely not
// out of laziness ;)
void check_flag(foo_t* f) {
while(f->flag)
pthread_cond_wait(&f->c, &f->m);
}
Run Code Online (Sandbox Code Playgroud)
C标准中是否有任何内容阻止优化器将check_flag重写为:
void check_flag(foo_t* f) {
bool cache = f->flag;
while(cache)
pthread_cond_wait(&f->c, &f->m);
}
Run Code Online (Sandbox Code Playgroud)
换句话说,每次循环时生成的代码是否必须跟随f指针,或者编译器是否可以自由地取消引用?
如果它可以自由拉出来,有什么办法可以防止这种情况发生吗?我需要在某处撒一个volatile关键字吗?它不能是check_flag参数,因为我计划在这个结构中有其他变量,我不介意编译器这样优化.
可能我不得不诉诸:
void check_flag(foo_t* f) {
volatile bool* cache …Run Code Online (Sandbox Code Playgroud)