Pthread Mutex lock unlock by different threads
linux, mutex, pthreads
Solution
What you've done is simply not legal, and the behavior is undefined. Mutexes only exclude threads that play by the rules. If you tried to lock mutex1 from thread 2, the thread would be blocked, of course; that's the required thing to do. There's nothing in the spec that says what happens if you try to unlock a mutex you don't own!
Problem
A Naive question .. I read before saying - "A MUTEX has to be unlocked only by the thread that locked it." But I have written a program where THREAD1 locks mutexVar and goes for a sleep. Then THREAD2 can directly unlock mutexVar do some operations and return. ==> I know everyone say why I am doing so ?? But my question is - Is this a right behaviour of MUTEX ?? ==> Adding the sample code ``` void *functionC() { pthread_mutex_lock( &mutex1 ); counter++; sleep(10); printf("Thread01: Counter value: %d\n",counter); pthread_mutex_unlock( &mutex1 ); } void *functionD() { pthread_mutex_unlock( &mutex1 ); pthread_mutex_lock( &mutex1 ); counter=10; printf("Counter value: %d\n",counter); } int main() { int rc1, rc2; pthread_t thread1, thread2; if(pthread_mutex_init(&mutex1, NULL)) printf("Error while using pthread_mutex_init\n"); if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) ) { printf("Thread creation failed: %d\n", rc1); } if( (rc2=pthread_create( &thread2, NULL, &functionD, NULL)) ) { printf("Thread creation failed: %d\n", rc2); } ```