简体   繁体   English

pthread_cond_t条件下的易失变量

[英]Volatile variable in condition for pthread_cond_t

If I have a piece of code like this 如果我有一段这样的代码

pthread_cond_t c;
pthread_mutex_t m;
int var = 0;

void some_function(int *some_variable)
{
    pthread_mutex_lock(&m);
    while(*some_variable != 123)
        pthread_cond_wait(&c, &m);
    pthread_mutex_unlock(&m);
    // *some_variable++; (1)
}

void some_another_fun(int *some_variable)
{
    pthread_mutex_lock(&m);
    *some_variable = 123;
    pthread_cond_signal(&c);
    pthread_mutex_unlock(&m);
}

int main()
{
    // run 1 thread for some_function
    // and one for some_another_fun
    // pass `&var` to both of them
}

Should I declare some_variable or var as volatile in this case? 在这种情况下,我应该将some_variablevar声明为volatile吗? Should I declare it as volatile if (1) is uncommented (ie *some_variable changes in some_function )? 如果(1)不加注释(即*some_variable some_function *some_variable变化),我是否应该将其声明为volatile?

Can a compiler cache *some_variable value in a register before executing while and never update it again? 编译器可以在执行while之前在寄存器中缓存*some_variable值, while再也不会对其进行更新了吗?

I don't fully understand when I should use volatile keyword (even this answers has some contradiction and disagreements) thus this question. 我不完全了解何时应该使用volatile关键字(即使答案也存在一些矛盾和分歧),因此这个问题。

The volatile is not needed because pthread functions contain a memory fence. 不需要volatile,因为pthread函数包含一个内存屏障。 See an answer to a similar question: Does pthread_mutex_lock contains memory fence instruction? 看到一个类似问题的答案: pthread_mutex_lock是否包含内存隔离指令?

An important thing to note is that volatile does not mean that the access must be performed in any particular order compared to non-volatile accesses. 要注意的重要一点是,与非易失性访问相比,易失性并不意味着必须以任何特定顺序执行访问。 This is why a memory fence is needed in inter-thread communication, instead of just having some global flags that we mark volatile(unless we mark everything in a program as volatile). 这就是为什么在线程间通信中需要一个内存屏障的原因,而不仅仅是拥有一些我们标记为volatile的全局标志(除非我们将程序中的所有内容都标记为volatile)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM