gpt4 book ai didi

c - pthread_cond_t 条件下的可变变量

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:32 25 4
gpt4 key购买 nike

如果我有一段这样的代码

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 声明为 volatile 吗?如果 (1) 未注释(即 *some_variable 更改 some_function),我是否应该将其声明为 volatile?

编译器能否在执行 while 之前将 *some_variable 值缓存在寄存器中,并且不再更新它?

我不完全明白什么时候应该使用volatile关键字(甚至this答案也有一些矛盾和分歧)所以这个问题。

最佳答案

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

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

关于c - pthread_cond_t 条件下的可变变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48963792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com