[ACCEPTED]-Pthread Mutex lock unlock by different threads-mutex

Accepted answer
Score: 26

Pthreads has 3 different kinds of mutexes: Fast 9 mutex, recursive mutex, and error checking 8 mutex. You used a fast mutex which, for 7 performance reasons, will not check for 6 this error. If you use the error checking 5 mutex on Linux you will find you get the 4 results you expect.

Below is a small hack 3 of your program as an example and proof. It 2 locks the mutex in main() and the unlock 1 in the created thread will fail.

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

/*** NOTE THE ATTR INITIALIZER HERE! ***/
pthread_mutex_t mutex1 = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;

int counter = 0;


void *functionD(void* data)
{
   int rc;

   if ((rc = pthread_mutex_unlock(&mutex1)) != 0)
   {
       errno = rc;
       perror("other thread unlock result");
       exit(1);
   }

   pthread_mutex_lock(&mutex1);
   counter=10;
   printf("Thread02: Counter value: %d\n",counter);

   return(data);
}


int main(int argc, char *argv[])
{
   int rc1;
   pthread_t thread1;

   if ((rc1 = pthread_mutex_lock(&mutex1)) != 0)
   {
       errno = rc1;
       perror("main lock result");
   }

   if( (rc1 = pthread_create(&thread1, NULL, &functionD, NULL)))
   {
      printf("Thread creation failed: %d\n", rc1);
   }

   pthread_join(thread1, NULL);
}
Score: 24

What you've done is simply not legal, and 7 the behavior is undefined. Mutexes only 6 exclude threads that play by the rules. If 5 you tried to lock mutex1 from thread 2, the 4 thread would be blocked, of course; that's 3 the required thing to do. There's nothing 2 in the spec that says what happens if you 1 try to unlock a mutex you don't own!

More Related questions