March 19, 2024, 02:59:51 AM

News : LinuxSolved.com Linux Help Community Forum..


Author Topic: Mutex Operation Examination  (Read 6992 times)

Offline Mavrek

  • New Member
  • Posts: 1
Mutex Operation Examination
« on: July 29, 2012, 05:47:38 PM »
Hi,

This is my first post here.

I would like to know the operation of mutex, so i wrote a program with two threads and each access the same  global variable, hence require the mutex.

I actually like to simulate the below behaviour.
Thread1 locks the mutex.
Thread2 try to lock the mutex and fails.

i have tried in some different ways but never i got to see the behaviour what i mentioned.
i tried keeping sleep(5) in each thread , all it is doing is wait till the thread terminates and continue with the rest.

what i expect is when some thread is sleeping other will get a chance to execute, but its not happening here.

can somebody please guide me how to simulate the behaviour i wanted.

NP: one more thing is there is no difference in the out put even if i remove the mutex control.



Thanks in Advance.


Code: [Select]

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

pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;

void *fun1(void* );
void *fun2(void* );

int arg = 20;

int main(  void ) {
        pthread_t tid1,tid2;
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        printf(" arg = %d\n", arg);
        pthread_create(&tid1, NULL, fun1,(void*)1);
        pthread_join(tid1,NULL);
        printf(" 1arg = %d\n", arg);
        pthread_create(&tid2, NULL, fun2,(void*)2);
        pthread_join(tid2,NULL);
        printf(" 2arg = %d\n", arg);
        printf("end\n");
        pthread_exit(NULL);

return 0;
}

void * fun1( void *p)
{
        int i;
        printf(" thrd %ld schded \n",(long) p);
        if ( -1 != pthread_mutex_lock(&mutex))
             if (arg == 20)
                 arg = 10;
      } else {
           printf(" Failed to acquire mutex in  1\n");
      } 
      //sleep(10);

      pthread_mutex_unlock(&mutex);
        pthread_exit(NULL);
}

void* fun2( void *p)
{
        printf(" thrd %ld schded \n",(long) p);
         if ( -1 != pthread_mutex_lock(&mutex)) {
        if (arg == 10)
                arg = 30;
       }else {
           printf(" Failed to acquire mutex in 2\n");
      } 
       
   pthread_mutex_unlock(&mutex);

        pthread_exit(NULL);
}

« Last Edit: July 29, 2012, 05:56:27 PM by Mavrek »