i wanna know what's the diffrent between mutex_lock and pthread_join?

138 Views Asked by At

What's the difference between mutex_lock and pthread_join in these two source codes? They seem both to do the same thing, making the main function wait for the thread to finish execution.

This code:

#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);

}

And this code :

#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);

}
1

There are 1 best solutions below

0
Jules On

not to be rude but you can easily find the difference by googling both functions name...

Though pthread_mutex_lock is for variables. It locks this variable for the current running thread. Thus no other thread can use it, they have to wait for pthread_mutex_unlock to use it.

pthread_join waits for the specified thread to finish it's execution before continuing

I encourage you to read the man pages, they are really self explanatory.