Home > Software design >  Mutex and order of execution
Mutex and order of execution

Time:12-02

First of all I am still new to posix programming and still understanding basic concepts. It is still not very clear for me how do pthread_mutex_lock pthread_mutex_unlock do work.

#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#inlcude <stdio.h>
pthread_mutex_t_mtx;
void* routine(void* i){
    int j;
    for(j = 0; j < 1000000;   j){
         pthread_mutex_lock(&mtx);
         printf("Inside thread %d\n", i);
         pthread_mutex_unlock(&mtx);
    }
    return NULL;
}

int main()
{
   pthread_t th[3];
   int i;
   pthread_mutex_init(&mtx, NULL);
   for(i = 1; i <= 2;   i)
   {
      if(pthread_create(th   i, NULL, routine, i){
           perror(NULL);  return 1;
      }
   }

   for(i = 1; i <=2;   i)
        pthread_join(th[i], NULL);

   return 0;
}

What should be the correct output of the above program ? I think that because of the lock and unlock of the mutex there would be 2000000 iterations, but it is not very clear for me the order that they are done in. Does the first thread execute the first 1000000 steps of the for? Does it even execute the first one of the 20000000 ? Or does this happen by a more chaotic order?

CodePudding user response:

Assuming that the mutex is a global one, you will get 2000000 messages, with 1000000 from each thread. The order of those is random, however they will not interfere each other as each print is protected by the mutex

EDIT: I just noticed, that you are joining before creating the next thread. Therfore first there will be all messages of the first, then of the second thread. In this case the mutex has no effect at all. The reason for the ordering is simply that you will not have more then one worker-thread running at the same time.

  • Related