Pthread Mutex锁定

时间:2011-07-14 13:48:22

标签: c pthreads mutex

我有一个关于静音处理的基本问题。 我有一个文件出现在2个其他线程(3个)中。我需要通过线程相互排除对它的访问。所以我在一个从thread1处理程序调用的函数中执行以下操作:

int sub_routine_thread1{

pthread_mutex_lock(&mut)
FILE *fp;
fp = fopen("myfile", "r");
if(fp == NULL){
return -1;
}
pthread_mutex_unlock(&mut)
return 0;
}

正如你所看到的,我已经知道如果文件指针返回NULL,那么我的互斥锁在这里被锁定并且解锁永远不会发生。所以我把它改成了以下内容:

int sub_routine_thread1{

pthread_mutex_lock(&mut)
FILE *fp;
fp = fopen("myfile", "r");
if(fp == NULL){
   pthread_mutex_unlock(&mut)
   return -1;
}
pthread_mutex_unlock(&mut)
return 0;
}

但是在此之后虽然我有一种不好的感觉,但这并不是应该完成互斥锁定的方式。我偶然发现了一些关于清理处理程序的事情,也许我认为这是我必须编写的代码:

int sub_routine_thread1{
     pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
     pthread_mutex_lock(&mut);
     FILE *fp;
     fp = fopen("myfile", "r");
     if(fp == NULL){
     return -1;
     }
     pthread_cleanup_pop(1);
     return 0;
}

这是正确的方法吗?你能澄清一下吗?

2 个答案:

答案 0 :(得分:1)

首先

if(fp == NULL){
    return -1;
    pthread_mutex_unlock(&mut); /* This is never reached. */
}

if(fp == NULL){
    pthread_mutex_unlock(&mut); /* Probably what you want. */
    return NULL;
}

其次,cleanup handlers非常酷且有用,但只有在使用pthread_cancel取消线程时才会调用它们。当线程正常退出时,它们不会被调用(并且返回被认为是正常的)。

答案 1 :(得分:1)

  

但是在此之后虽然我感觉不好,但这并不是互斥锁行为的方式。

是的。你的第二个例子非常好。 pthread_cleanup_push用于在线程被取消时运行函数,这不是你应该在这里使用的。

尽管如此,我可能更喜欢做类似

的事情
int sub_routine_thread1() {
  FILE *fp;
  int ret = -1;
  pthread_mutex_lock(&mut)
  fp = fopen("myfile", "r");
  if(fp != NULL){
     //do_stuff_unlocked(fp);
     ret = 0;
  }
  pthread_mutex_unlock(&mut)
  return ret;
}