2

I'm running the following code (code at the bottom) to get a feel of how to work with threads and mutex's. And from how I thought mutex's work is that once there is a locked code section marked by pthread_mutex_lock then any other thread cannot advance until that thread is unlocked. So if that were the case I would be getting this output:

TEST
0
TEST
1
TEST
2
TEST
3
TEST
4

But instead I get output like this (varies per run):

TEST
0
TEST
1
TEST
2
TEST
TEST
3
4

So I'm wondering if my understanding of how the mutex work is wrong, or if I am using them incorrectly. Either way how would I go about getting the output I'm expecting using threads? Thanks for all the help in advance.

int counter;
pthread_mutex_t lock;

void * threadAction(void * unused);

int main()
{
  pthread_t tid[5];
  int i = 0;
  counter = -1;
  for(i = 0; i < 5; i++
  {
    pthread_create(&tid[i], NULL, threadAction, NULL);
  }

  for(i = 0; i < 5; i++
  {
    pthread_join(tid[i], NULL);
  }

}

void * threadAction(void * unused)
{   
  pthread_mutex_lock(&lock); 
  printf("TEST\n");
  counter++;
  printf("%d\n", counter);
  pthread_mutex_unlock(&lock);
  return NULL;
}
Kenshin
  • 177
  • 1
  • 9

0 Answers0