0

I am confused as to mutex works on code segment or variables in a code segment.

In the example below, mutex will prevent two threads trying to access mysum at the same time either from func1 or func2 or only the code-segment between mutex lock and unlock is protected

   .
   .
     pthread_mutex_t myMutex;
     int mysum;

  void func1(){
  .
  .
  .

  pthread_mutex_lock (&myMutex);
     mysum--;
     printf("Thread %ld did mysum=%d\n",id,mysum);
  pthread_mutex_unlock (&myMutex);
  .
  .
  }

  void func2(){
  .
  .
  .
  mysum++;

  pthread_mutex_lock (&myMutex);
     mysum++;
     printf("Thread %ld did mysum=%d\n",id,mysum);
  pthread_mutex_unlock (&myMutex);
  .
  .
  }

  int main (int argc, char *argv[])
  {
    pthread_mutex_init(&myMutex, NULL);
  .
  .

    pthread_create(&callThd1, &attr, func1, NULL); 

    pthread_create(&callThd2, &attr, func2, NULL); 
      pthread_create(&callThd3, &attr, func1, NULL); 

    pthread_create(&callThd4, &attr, func2, NULL); 
    pthread_create(&callThd5, &attr, func1, NULL); 

    pthread_create(&callThd6, &attr, func2, NULL); 
  .
  .


    pthread_mutex_destroy(&myMutex);
  .
  .

  }
Aadishri
  • 1,341
  • 2
  • 18
  • 26
  • Mutex is only needed to protect data. Code, (unless self-modifying, in which case stop doing that!), is inherently thread-safe. – Martin James Jan 17 '13 at 16:42

1 Answers1

0

The mutex only provides mutual exclusion between the code sections that lie between pthread_mutex_lock() and pthread_mutex_unlock() (these are known as critical sections).

There's no direct link between the mutex and the shared data it's protecting - it is up to you to ensure that you only access the shared data with the appropriate mutex locked.

caf
  • 233,326
  • 40
  • 323
  • 462
  • So, I understand there exists no explicit programming construct to protect variables and this has to be achieved by efficient use of mutual exclusion and critical sections. In that case, in the example above, I will not be able to control mysum in func1 and func2, which are called in different threads. Can semaphore help here? – Aadishri Jan 18 '13 at 06:46
  • I found a post http://stackoverflow.com/questions/5454746/pthread-mutex-lock-unlock-by-different-threads?rq=1 that answered the question above.Thanks! – Aadishri Jan 18 '13 at 07:04