Pthreads条件变量错误的行为

时间:2014-10-23 01:49:34

标签: linux multithreading pthreads

有没有人试过一个例子 https://computing.llnl.gov/tutorials/pthreads/samples/condvar.c

这个例子调用3个线程,一个主线程watch_count()执行直到到达pthread_cond_wait(),另外两个线程inc_count()增加一个" count"反过来。当计数等于预定阈值时,调用pthread_cond_signal(),然后解锁inc_count()的pthread并返回主线程中pthread_cond_wait()之后的代码(已锁定)。但是,我发现有时当inc_count()到达pthread_cond_signal()时,这个线程被解锁并且由watch_count()中的pthread_cond_wait()执行锁定,另一个inc_count()执行,因此计数再次增加"再次#34 ;。但是,这不应该在理论上发生。我发现当我调整计数限制时,行为是不同的。

请看下面的照片,顶部错误是因为当thread3达到阈值(11)时,它会发送信号。然后,在到达watch_count()之前,线程2拦截。

但是,当COUNT_LIMIT = 12时,一切都与我想象的完全相同

任何人都可以帮助我吗?

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

#define NUM_THREADS  3
#define TCOUNT 10
#define COUNT_LIMIT 12

int     count = 0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;

void *inc_count(void *t) 
{
  int i;
  long my_id = (long)t;

  for (i=0; i < TCOUNT; i++) {
    pthread_mutex_lock(&count_mutex);
    count++;

    /* 
    Check the value of count and signal waiting thread when condition is
    reached.  Note that this occurs while mutex is locked. 
    */
    if (count == COUNT_LIMIT) {
      printf("inc_count(): thread %ld, count = %d  Threshold reached. ",
             my_id, count);
      pthread_cond_signal(&count_threshold_cv);
      printf("Just sent signal.\n");
      }
    printf("inc_count(): thread %ld, count = %d, unlocking mutex\n", 
       my_id, count);
    pthread_mutex_unlock(&count_mutex);

    /* Do some work so threads can alternate on mutex lock */
    sleep(1);
    }
  pthread_exit(NULL);
}

void *watch_count(void *t) 
{
  long my_id = (long)t;

  printf("Starting watch_count(): thread %ld\n", my_id);

  /*
  Lock mutex and wait for signal.  Note that the pthread_cond_wait routine
  will automatically and atomically unlock mutex while it waits. 
  Also, note that if COUNT_LIMIT is reached before this routine is run by
  the waiting thread, the loop will be skipped to prevent pthread_cond_wait
  from never returning.
  */
  pthread_mutex_lock(&count_mutex);
  while (count < COUNT_LIMIT) {
    printf("watch_count(): thread %ld Count= %d. Going into wait...\n", my_id,count);
    pthread_cond_wait(&count_threshold_cv, &count_mutex);
    printf("watch_count(): thread %ld Condition signal received. Count= %d\n", my_id,count);
    printf("watch_count(): thread %ld Updating the value of count...\n", my_id,count);
    count += 125;
    printf("watch_count(): thread %ld count now = %d.\n", my_id, count);
    }
  printf("watch_count(): thread %ld Unlocking mutex.\n", my_id);
  pthread_mutex_unlock(&count_mutex);
  pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
  int i, rc; 
  long t1=1, t2=2, t3=3;
  pthread_t threads[3];
  pthread_attr_t attr;

  /* Initialize mutex and condition variable objects */
  pthread_mutex_init(&count_mutex, NULL);
  pthread_cond_init (&count_threshold_cv, NULL);

  /* For portability, explicitly create threads in a joinable state */
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  pthread_create(&threads[0], &attr, watch_count, (void *)t1);
  pthread_create(&threads[1], &attr, inc_count, (void *)t2);
  pthread_create(&threads[2], &attr, inc_count, (void *)t3);

  /* Wait for all threads to complete */
  for (i = 0; i < NUM_THREADS; i++) {
    pthread_join(threads[i], NULL);
  }
  printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\n", 
          NUM_THREADS, count);

  /* Clean up and exit */
  pthread_attr_destroy(&attr);
  pthread_mutex_destroy(&count_mutex);
  pthread_cond_destroy(&count_threshold_cv);
  pthread_exit (NULL);

}

enter image description here

1 个答案:

答案 0 :(得分:0)

inc_count()个帖子每次加1到TCOUNT次。将计数递增到COUNT_LIMIT的那个将对watch_count()线程进行cond_signal。 printf()的神奇之处在于你会看到每个线程的输出合理地交错。

您似乎假设只要pthread_cond_signal()完成,watch_count()线程就会运行。它可能会这样做,但至少会立即停止在互斥锁上,直到信令线程解锁互斥锁为止。如果另一个inc_count()线程此时也在等待互斥锁,那么它可能在watch_count()线程之前或之后运行。可能是线程在fifo顺序中等待互斥锁...但由于你不知道它们到达了什么顺序,这不允许你预测它们将以什么顺序运行!


此外:假设watch_count()在更新计数之前要等到count >= COUNT_LIMIT,那么应该将内容移出while()循环:

  while (count < COUNT_LIMIT) {
    printf("watch_count(): thread %ld Count= %d. Going into wait...\n", my_id,count);
    pthread_cond_wait(&count_threshold_cv, &count_mutex);
    printf("watch_count(): thread %ld Condition signal received. Count= %d\n", my_id,count);
    }
  printf("watch_count(): thread %ld Updating the value of count...\n", my_id,count);
  count += 125;
  printf("watch_count(): thread %ld count now = %d.\n", my_id, count);

要理解的关键是条件(所谓的)“变量”根本没有内存,所以在等待某个状态设置之前,你需要检查状态是否尚未设置(并且条件已经发出信号 - 只有服务员才会生效,如果没有服务员则会被遗忘。

另一个问题是条件可以(在某些情况下)在发出信号时释放多个服务员...所以通常在pthread_cond_wait()周围放置一个while循环并使用某些状态(在互斥锁下) )控制pthread_cond_signal()之后有多少服务员继续。