pthread_barrier无法正常工作(在C中)

时间:2017-03-15 21:13:13

标签: c multithreading

我有一个main函数,用于初始化pthread_barrier,如下所示:

pthread_barrier_t     barrier;
pthread_barrierattr_t attr;

if (pthread_barrierattr_init(&attr) != 0 ||
    pthread_barrier_init(&barrier, &attr, nb_threads) != 0)
  return ;
int i = 0;
while (i < nb_threads)
    {
      threads[i].barrier = &barrier;
      threads[i].attr = &attr;
      // ...
      if ((error = pthread_create(&threads[i].thread, NULL, core,
                                  (void *)&threads[i])) != 0)
        return (thread_create_error(error));
      i++;
    }
  i = -1;
  while (++i < nb_philo)
    pthread_join(threads[i].thread, NULL);

并且,在每个线程中,我都有一个指向我的屏障变量的指针。

并且,在每个线程的函数中(每个线程都是相同的),我在循环中有pthread_barrier_wait(thread->barrier)函数。

void thread_func(...)
{
    int i = 0;

    while (i < nb_threads)
    {
       //...Doing some stuff
       pthread_barrier_wait(thread->barrier)
       i++;
    }
}

在大多数情况下,它工作得很好,但很少(并且随机??),它什么都不输出,程序卡住了,似乎屏障还在等待。有时,pthread_barrier_wait(thread->barrier)函数返回-1(大多数情况下它返回0)。

我该如何解决这个问题?这是在C中使用障碍的好方法吗?没有互斥,这是正常的吗?为什么有时程序仍然等待,有时候没有?

输出似乎在开始时起作用,经过几次迭代后,它完全失败了:

thread 1 begin
thread 2 begin
thread 3 begin
...
thread 1 end
thread 2 end
thread 3 end
...

after few iterations:

thread 1 begin
thread 2 begin
thread 3 end

...

thread 3 begin
thread 1 end
thread 2 end
...

非常感谢

0 个答案:

没有答案