如果我有一些代碼,看起來類似:以下指導
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);
}
有什麼C標準防止優化器重寫check_flag爲:
void check_flag(foo_t* f) {
bool cache = f->flag;
while(cache)
pthread_cond_wait(&f->c, &f->m);
}
在其他字,那麼生成的代碼是否有在每次遍歷循環時都遵循f
指針,或者編譯器是否可以自由地將取消引用取出?
如果它是自由拉出來,有沒有什麼辦法來防止這種情況?我需要在某處撒上一個易揮發的關鍵字嗎?它不能是check_flag
的參數,因爲我計劃在這個結構中有其他變量,我不介意像這樣編譯器優化。
我可能訴諸:
void check_flag(foo_t* f) {
volatile bool* cache = &f->some_flag;
while(*cache)
pthread_cond_wait(&f->c, &f->m);
}
+1在嘗試通過試錯法編寫線程代碼之前思考此類問題! – 2011-01-14 01:17:29