gpt4 book ai didi

c - Pthread 互斥锁

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:50 24 4
gpt4 key购买 nike

我有一个关于互斥处理的基本问题。我有一个文件出现在其他 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;
}

这是正确的方法吗?你能解释一下吗?

最佳答案

But after this though I have a bad feeling this is not the way mutex loxking should be done.

是的。你的第二个例子非常好。 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;
}

关于c - Pthread 互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6694186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com