pandaPanda
pandaPanda

Reputation: 1

Why and how is mutex working without initialising it using pthread_mutex_init()?

I am new to pthreads. I tried out a basic code from https://www.youtube.com/watch?v=xoXzp4B8aQk&list=PLfqABt5AS4FmuQf70psXrsMLEDQXNkLq2&index=5. I forgot to initialise the mutex using pthread_mutex_init() function, but I ended up getting the correct output.

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

int mail_count;
pthread_mutex_t mutex;

void *mail()
{
    for(int i = 0; i < 1000000; i++)
    {
        pthread_mutex_lock(&mutex);
        mail_count++;
        pthread_mutex_unlock(&mutex);
    }
}


int main()
{
    pthread_t p1, p2;

    pthread_create(&p1,NULL, &mail, NULL );
    pthread_create(&p2,NULL, &mail, NULL );
    pthread_join(p1, NULL);
    pthread_join(p2, NULL);

    printf("%d - no of mails read\n\n", mail_count);
    return 0;
}

And the output is : 2000000 - no of mails read

Is pthread_mutex_init() necessary?

Upvotes: 0

Views: 331

Answers (1)

Michael Walsh Pedersen
Michael Walsh Pedersen

Reputation: 474

You need to initialize the mutex before using it, otherwise it's undefined behavior . If you don't want to call pthread_mutex_init(), you can instead do:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

Upvotes: 2

Related Questions