我需要调用一个返回唯一 id 的函数,
int getid()
{
static id=0;
id++;
return id;
}
多个线程需要调用这个函数,我的问题是我不确定我需要在哪里锁定互斥量,
调用函数前后需要加锁吗
pthread_mutex_lock( &id );
int id = getid()
pthread_mutex_unlock( &id );
有人可以帮我吗?
最佳答案
只要在访问共享状态之前锁定在何处并不重要。如果互斥锁在函数内部,就不太容易出错。像这样最小的东西会起作用:
int getid()
{
static int id=0;
pthread_mutex_lock( &mutex );
int newId = ++id;
pthread_mutex_unlock( &mutex );
return newId;
}
关于静态变量的初始化是线程安全的,您可能需要研究一些问题。
关于linux - 与 pthread 互斥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13436673/