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?
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:
There are some issues around the initialization of the static variable being thread safe that you may want to look into.