Pthread 互斥锁
我有一个关于互斥处理的基本问题。 我有一个文件出现在另外 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;
}
这是正确的方法吗?你能澄清一下吗?
I have a basic question on mutext handling.
I have a file which appears at 2 other threads(out of 3). I need to mutually exclude access to it by a thread. So I do the following in a function called from the thread1 handler:
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;
}
As you can see I already know that if the file pointer return a NULL, then my mutex gets locked here and the unlocking never happens. So I changed it to the following:
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;
}
But after this though I have a bad feeling this is not the way mutex locking should be done. I chanced upon something about cleanup handlers and perhaps thought this is how I must code:
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;
}
Is this the right way? Can you please clarify?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。你的第二个例子非常好。 pthread_cleanup_push 用于在线程取消时运行函数,这不是您应该在此处使用的。
尽管如此,我可能更喜欢做类似的事情
Yes it is. Your second example is perfectly fine. pthread_cleanup_push is used to run functions when the thread is cancelled, that's not what you should use here.
Allthough, I'd probably prefer to do something like
首先,
其次,清理处理程序确实非常酷且有用,但是仅当您使用 pthread_cancel 取消线程时才会调用它们。当线程正常退出时(并且返回被认为是正常的),它们不会被调用。
First of all
Second, cleanup handlers are really really cool and useful, but they are only called when you cancel the thread using
pthread_cancel
. They are not called when the thread exits normally (and that return is considered normal).