3
votes

I have written the following program to implement two threads in POSIX. There is a global shared variable sum, which is being accessed by two different threads simultaneously. I have used mutex lock and unlock inside each thread while accessing the shared variable. I have a question. Here I have used the samed mutex lock (pthread_mutex_lock(&mutex))inside the two threads. What will Happen if I use two different mutex lock and unlock inside the threads (such as pthread_mutex_lock(&mutex)) in thread1 and pthread_mutex_lock(&mutex1) in thread2. I have commented out the line of confusion in the code.

My sample code fragment:

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex1=PTHREAD_MUTEX_INITIALIZER;
int sum=0;
void * threadFunc1(void * arg)
{
    int i;
    for(i=1;i<100;i++)
    {
        printf("%s\n",(char*)arg);
        pthread_mutex_lock(&mutex)
        sum++;
        pthread_mutex_unlock(&mutex)
        sleep(1);
    }
}

void * threadFunc2(void * arg)
{
    int i;
    for(i=1;i<100;i++)
    {
            printf("%s\n",(char*)arg);
            pthread_mutex_lock(&mutex)  //what will happen if I use mutex1 here
            sum--;
            pthread_mutex_lock(&mutex)  //what will happen if I use mutex1 here
            sleep(1);
    }
}


int main(void)
{   
    pthread_t thread1;
    pthread_t thread2;


    char * message1 = "i am thread 1";
    char * message2 = "i am thread 2";  

    pthread_create(&thread1,NULL,threadFunc1,(void*)message1 );
    pthread_create(&thread2,NULL,threadFunc2,(void*)message2 );

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);

    return 0;

}

What is the basic difference between using the same mutex locks and different mutex lock in accessing a shared variable?

1
You do you use the mutex mutex1 in you code at all!Ed Heal

1 Answers

4
votes

The purpose of the mutex is to prevent one thread from accessing the shared variable while another thread is, or might be, modifying it. The semantics of a mutex are that two threads cannot lock the same mutex at the same time. If you use two different mutexes, you don't prevent one thread from accessing the shared variable while another thread is modifying it, since threads can hold different mutexes at the same time. So the code will no longer be guaranteed to work.