【问题标题】:mutex with pthread带 pthread 的互斥锁
【发布时间】:2012-11-18 01:38:44
【问题描述】:

我需要调用一个返回唯一id的函数,

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

}

多个线程需要调用这个函数,我的问题是我不确定我需要在哪里锁定互斥锁,

调用如下函数前后是否需要加锁

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

有人可以帮我吗?

【问题讨论】:

    标签: linux multithreading synchronization pthreads


    【解决方案1】:

    只要是在访问共享状态之前,它在哪里被锁定并不重要。如果互斥锁在函数内部,则不太容易出错。像这样最小的东西会起作用:

    int getid()
    {
    static int id=0;
    
    pthread_mutex_lock( &mutex );
    int newId = ++id;
    pthread_mutex_unlock( &mutex );
    
    return newId; 
    }
    

    静态变量的初始化存在一些线程安全的问题,您可能需要研究一下。

    【讨论】:

    • 我确实做到了,我在想的是return newId,我的意思是,当函数被调用然后到达return,然后再次调用它,会不会影响第一次返回?
    • 由于newId不是静态变量,所以会位于调用线程的栈中。每个线程都有一个单独的堆栈,因此它们不会相互干扰。
    • 谢谢,可以将 id 设为全局变量吗?在这种情况下,线程中的静态变量不安全,我不会有任何问题?
    【解决方案2】:

    对于单个整数,您不需要完整的互斥体,atomic increment 就足够了:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 2013-06-06
      • 2015-07-20
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多