Home > Mobile >  How to properly sync multithreading with mutex in c?
How to properly sync multithreading with mutex in c?

Time:11-29

How should i properly sync threads with mutex? I'm trying a simple "sync" using mutex, something really small, like just printing a string containing the number of the thread. snippet here:

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

#define MAX_RESOURCE 5
#define NO_THREADS 5
int res_available = MAX_RESOURCE;
pthread_mutex_t mtx;
struct count { int no;};

void *
use_res(void *v) {
 pthread_mutex_lock(&mtx);
 struct count *p = (struct count *) v;
 printf("--thread no %d :" p->nr);
 return NULL;
}


int main(){
  pthread_t thr[NO_THREADS];
  pthread_mutex_init(&mtx, NULL);
  for(int i=0; i<N0_THREADS; i  ){
     struct count *c = malloc(sizeof(struct count));
     c->nr = i;
     pthread_create(thr[i], NULL, use_res, c))
     }
  for(int i=0; i<NO_THREADS; i  ) {
     pthread_join(thr[i], NULL);
     }
  return 0;
}

Fact is, when executed, the sync doesn't actually occur, actually, what it does occur, is still that "race condition", making the program to print something else everytime.

My question is, how do i stop this race condition? I don't know if i'm using correctly this lock and unlock thing.

CodePudding user response:

You need to release mutex when your thread function finish, also add \n at the end of print, because stdout will buffer this text:

void *
use_res(void *v) {
 pthread_mutex_lock(&mtx);
 struct count *p = (struct count *) v;
 printf("--thread no %d :\n" p->no);
 pthread_mutex_unlock(&mtx);
 return NULL;
}
  • Related