1
votes

I need to call a function that returns a unique id,

int getid()
{
static id=0;
id++;
return id;

}

Multiple threads need to call this function, my problem is I'm not sure where I need to lock the mutex,

Do I need to lock before and after calling the function like below

  pthread_mutex_lock( &id );
  int id = getid()
  pthread_mutex_unlock( &id );

can someone help me with that please?

2

2 Answers

3
votes

It doesn't really matter where it was locked as long as it was before the access to the shared state. It would be less prone to errors if the mutex locking was inside the function. Something minimal like this would work:

int getid()
{
static int id=0;

pthread_mutex_lock( &mutex );
int newId = ++id;
pthread_mutex_unlock( &mutex );

return newId; 
}

There are some issues around the initialization of the static variable being thread safe that you may want to look into.

2
votes

For a single integer you don't need a full mutex, atomic increment would be enough:

int getid() {
    static int id = 0;
    return __sync_fetch_and_add( &id, 1 );
}