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.