【问题标题】:i wanna know what's the diffrent between mutex_lock and pthread_join? [duplicate]我想知道互斥锁和pthread_join有什么区别? [复制]
【发布时间】:2022-02-05 00:53:37
【问题描述】:

这两个源码中mutex_lockpthread_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


【解决方案1】:

不要粗鲁,但您可以通过谷歌搜索两个函数名称轻松找到区别...

虽然pthread_mutex_lock 用于变量。它为当前正在运行的线程锁定此变量。因此没有其他线程可以使用它,它们必须等待pthread_mutex_unlock 才能使用它。

pthread_join 等待指定线程完成执行后再继续

我鼓励您阅读手册页,它们真的很容易解释。

【讨论】:

    猜你喜欢
    • 2011-08-28
    • 2012-03-12
    • 2011-04-13
    • 2010-10-22
    • 2014-09-26
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多