pthread_cond_t条件下的易失性变量

时间:2018-02-24 14:15:47

标签: c multithreading pthreads

如果我有一段这样的代码

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
}

在这种情况下,我应该声明some_variablevar是不稳定的吗?如果(1)被取消注释(即*some_variable中的some_function更改),我应该将其声明为volatile吗?

编译器在执行*some_variable之前是否可以在寄存器中缓存while并且永远不会再次更新它?

我不完全明白何时应该使用volatile关键字(即使this答案有一些矛盾和分歧)因此这个问题。

1 个答案:

答案 0 :(得分:2)

不需要volatile,因为pthread函数包含内存栅栏。查看类似问题的答案:Does pthread_mutex_lock contains memory fence instruction?

需要注意的一点是,与非易失性访问相比,volatile并不意味着必须以任何特定顺序执行访问。这就是为什么在线程间通信中需要内存栅栏的原因,而不是只有一些我们标记为volatile的全局标志(除非我们将程序中的所有内容标记为volatile)。