【发布时间】:2022-02-05 00:53:37
【问题描述】:
这两个源码中mutex_lock和pthread_join有什么区别?它们似乎都在做同样的事情,让 main 函数等待线程完成执行。
这段代码:
#include "philo.h"
typedef struct s_bablo
{
pthread_mutex_t mutex;
} t_bablo;
void *myturn(void *arg)
{
t_bablo *bablo = (t_bablo *)arg;
int i = 0;
while(i < 10)
{
printf("My Turn ! %d\n", i);
i++;
sleep(1);
}
pthread_mutex_unlock(&bablo->mutex);
}
void *yourturn()
{
int i = 0;
while(i < 5)
{
printf("Your Turn ! %d\n", i);
i++;
sleep(1);
}
}
int main ()
{
t_bablo bablo;
pthread_mutex_init(&bablo.mutex, NULL);
pthread_t ph;
pthread_mutex_lock(&bablo.mutex);
pthread_create(&ph, NULL, myturn, &bablo);
yourturn();
pthread_mutex_lock(&bablo.mutex);
}
还有这段代码:
#include "philo.h"
void *myturn(void *arg)
{
int i = 0;
while(i < 10)
{
printf("My Turn ! %d\n", i);
i++;
sleep(1);
}
}
void *yourturn()
{
int i = 0;
while(i < 5)
{
printf("Your Turn ! %d\n", i);
i++;
sleep(1);
}
}
int main ()
{
pthread_t ph;
pthread_create(&ph, NULL, myturn, NULL);
yourturn();
pthread_join(ph, NULL);
}
【问题讨论】:
-
您好,请编辑您的代码以使其可读。
-
这个Difference between mutex lock and pthread_join 回答你的问题了吗?
-
他们完全不同。一个等待锁被清除,另一个等待线程完成。
-
只有当线程在其运行的整个时间内锁定互斥锁时,它们才等效。
-
基于互斥锁的版本具有未定义的行为,因为它依赖于不同的线程来解锁互斥锁而不是锁定它的线程。您可以使用信号量来做到这一点,但不能使用互斥锁。
标签: c pthreads mutex pthread-join