【发布时间】:2016-09-05 03:48:33
【问题描述】:
首先,我有一种直觉,在 if 语句中,如果我正在使用该变量,它会被视为读取该变量,所以我也应该在那里用互斥锁锁定它(如果另一个 pthread 可能正在做一些事情用它)。我应该锁定它吗?
下面给出简化的示例情况。
在一个线程中,我使用以下语句:
if(event){
// Should I or should I not lock event here to use it
// inside if statement?
pthread_mutex_lock(&mutex_event);
event = 0;
pthread_mutex_unlock(&mutex_event);
// blah blah code here
// blah blah code here
// blah blah code here
}
在我正在做的另一个线程中
pthread_mutex_lock(&mutex_event);
event = 1;
pthread_mutex_unlock(&mutex_event);
第二个问题,如果我确实需要锁定它,我应该如何以优雅的程序员方式来做呢?换句话说,什么是一般约定。我不喜欢下面的想法,因为我必须等待“if”中的所有行执行才能再次解锁互斥锁。
pthread_mutex_lock(&mutex_event);
if(event){
event = 0;
// blah blah code here
// blah blah code here
// blah blah code here
}
pthread_mutex_unlock(&mutex_event);
我同意这个想法,但它可能看起来更漂亮:
pthread_mutex_lock(&mutex_event);
if(event){
event = 0;
pthread_mutex_unlock(&mutex_event);
// blah blah code here
// blah blah code here
// blah blah code here
}
else
{
pthread_mutex_unlock(&mutex_event);
}
我发现使用 while 循环会变得更棘手,这是我得到的原始解决方案:
pthread_mutex_lock(&mutex_event);
store_event = event; // store_event is local
pthread_mutex_unlock(&mutex_event);
while(store_event){
// blah blah code here
// blah blah code here
// blah blah code here
}
【问题讨论】:
标签: c linux pthreads posix mutex