top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Mutex unlock from different thread?

+4 votes
525 views

There are two threads one takes lock and execute infinite loop. When ever other thread start execution before trying to take lock it unlocks the mutex.

Its a wrong behavior, how can I prevent this.

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

pthread_t callThd_one, callThd_two;
pthread_mutex_t mutexsum;

void *thread_one(void *arg)
{
   pthread_mutex_lock (&mutexsum);
   while(!sleep(1))
       printf("\n In thread One \n");

   pthread_mutex_unlock (&mutexsum);
   pthread_exit((void*) 0);
}

void *thread_two(void *arg)
{
   pthread_mutex_unlock (&mutexsum);
   //pthread_mutex_lock (&mutexsum);
   while(!sleep(1))
       printf("\n In thread two \n");

   pthread_mutex_unlock (&mutexsum);
   pthread_exit((void*) 0);
}

int main (int argc, char *argv[])
{
   void *status;
   pthread_attr_t attr;

   pthread_mutex_init(&mutexsum, NULL);

   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   pthread_create(&callThd_one, &attr, thread_one, NULL);
   pthread_create(&callThd_two, &attr, thread_two, NULL);

   pthread_attr_destroy(&attr);

   pthread_join(callThd_one, &status);
   pthread_join(callThd_two, &status);

   pthread_mutex_destroy(&mutexsum);
   pthread_exit(NULL);
}

Is there any way to sure that mutex should be unlock only by the thread which took lock.

posted Oct 14, 2013 by Vikas Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

This is incorrect way of mutex handling. This problem can be solved two ways

  1. instead trying pthread_mutex_unlock and pthread_mutex_lock one should use pthread_mutex_trylock to avoid deadlock scenarios
  2. if want to continue with same code use error checking mutex rather default.
answer Oct 18, 2013 by Pankaj Agarwal
Similar Questions
+2 votes

Here my doubt is about acquire mutex lock.

Here pthread_mutex_t lock ; is also a global variable shared to threads. Accessing of this global variable (lock) will it be shame as accessing of other global variables ? If same, then don't we face same problem what we will face for other global variables ? if not ,how this is discriminated from other global variables ?

+5 votes

Which one is better for which situation ??

+5 votes

What is structure padding and how it is used at processor level?

...