1

抱歉,如果问题标题令人困惑。我只是想把所有的东西放在一起。我有一段代码,如:

int newThread(int(*pfunc)())
{
   pthread_t tid;
   pthread_create(&tid, NULL, pfunc, NULL);
   int i = 0;
   while(threads[i] != 0 && i < MAX_NUM_THREADS)
   {
      if ((MAX_NUM_THREADS - 1) == i)
      {
        puts("We've run out of threads' number limit\n");
        return 1;
      }
      ++i;
   } 
   threads[i] = tid;
   pthread_join(tid, NULL);
   return 0;
}

threads[] 是一个全局数组。我想让这个函数可重入,但这意味着据我所知,我不应该使用全局变量。我想这是因为全局变量的值在某个时间是不可预测的。但在我的情况下,数组似乎是可以预测的。

  1. 可以吗,如果我用互斥锁锁定数组以使该函数可重入?
  2. 如果是,那么我该怎么做呢?只需在使用前锁定第一个元素并在使用后解锁?还是在访问时锁定/解锁每个元素更好?
  3. 这甚至可以使这个函数可重入吗?
4

1 回答 1

2

要说一个函数是可重入的,它应该只依赖局部变量被两个(或多个线程)同时调用并返回正确的结果。

如果函数依赖于一些共享数据,(我们不能真正让它可重入),如果对共享数据的所有访问都是序列化的,我们可以让它被两个(或更多)线程同时调用是线程安全的。

为了使您的函数线程安全,您应该锁定循环并插入threads[]. 如果你只锁定循环部分,有人可能会修改threads循环结束和 rank 做作之间的内容i

pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;

int newThread(int(*pfunc)())
{
   pthread_t tid;
   pthread_create(&tid, NULL, pfunc, NULL);
   int i = 0;
   pthread_mutex_lock(&mymutex);          // take the lock
   while(threads[i] != 0 && i < MAX_NUM_THREADS)
   {
      if ((MAX_NUM_THREADS - 1) == i)
      {
        puts("We've run out of threads' number limit\n");
        pthread_mutex_unlock(&mymutex);   // don't forget to release the lock here too :)
        return 1;
      }
      ++i;
   } 
   threads[i] = tid;
   pthread_mutex_unlock(&mymutex);        // release the lock
   pthread_join(tid, NULL);
   return 0;
}
于 2011-09-30T08:50:21.383 回答