我有一个关于静音处理的基本问题。我有一个文件,出现在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;
}这条路对吗?你能澄清一下吗?
发布于 2011-07-14 22:11:35
,但是在这之后,我有一种不好的感觉,这不是互斥锁定位的方式。
是的。您的第二个示例完全正确。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;
}发布于 2011-07-14 21:51:04
首先,
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取消线程时才会调用。当线程正常退出时,它们不会被调用(返回被认为是正常的)。
https://stackoverflow.com/questions/6694186
复制相似问题