【发布时间】:2018-02-24 14:15:47
【问题描述】:
如果我有这样一段代码
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_variable 或 var 声明为 volatile 吗?如果 (1) 未注释(即 *some_variable 更改为 some_function),我应该将其声明为 volatile 吗?
编译器能否在执行while 之前将*some_variable 值缓存在寄存器中并且不再更新它?
我不完全明白什么时候应该使用volatile 关键字(即使this 的答案也有一些矛盾和分歧)因此这个问题。
【问题讨论】:
-
您的代码示例出现了死锁。
some_function()锁定m并等待some_other_functon()修改共享变量,但这样做必须首先获取some_function()已锁定的m。它只会在some_other_functon()运行并首先锁定信号量时运行。 -
@Clifford 实际上我并没有尝试编写 100% 正确的代码,因为我只是想演示一般模式。不过,我不认为我理解你的评论。互斥锁
m将由pthread_cond_wait解锁,因此some_another_fun将能够获取它并将123 存储到some_variable -
我不是 pthreads 专家,所以你可能是正确的。我的经验是在嵌入式系统上使用 RTOS,坦率地说,POSIX 线程语义对我来说有点陌生。
标签: c multithreading pthreads