【问题标题】:Pthread condition variable and no deadlockPthread 条件变量且无死锁
【发布时间】:2017-08-11 05:22:00
【问题描述】:

在找话题的时候,我从here找到了代码。如您所见,两个函数线程都使用相同的mutex。那么,即使先前的线程拥有互斥锁,如何向其他线程发出信号或捕获信号并继续其功能?如何/为什么没有死锁?有点混乱。

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

pthread_mutex_t count_mutex     = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  condition_var   = PTHREAD_COND_INITIALIZER;

void *functionCount1();
void *functionCount2();
int  count = 0;
#define COUNT_DONE  10
#define COUNT_HALT1  3
#define COUNT_HALT2  6

main()
{
   pthread_t thread1, thread2;

   pthread_create( &thread1, NULL, &functionCount1, NULL);
   pthread_create( &thread2, NULL, &functionCount2, NULL);

   pthread_join( thread1, NULL);
   pthread_join( thread2, NULL);

   printf("Final count: %d\n",count);

   exit(EXIT_SUCCESS);
}

// Write numbers 1-3 and 8-10 as permitted by functionCount2()

void *functionCount1()
{
   for(;;)
   {
      // Lock mutex and then wait for signal to relase mutex
      pthread_mutex_lock( &count_mutex );     //     <---- Same mutex

      // Wait while functionCount2() operates on count
      // mutex unlocked if condition varialbe in functionCount2() signaled.
      pthread_cond_wait( &condition_var, &count_mutex );
      count++;
      printf("Counter value functionCount1: %d\n",count);

      pthread_mutex_unlock( &count_mutex );

      if(count >= COUNT_DONE) return(NULL);
    }
}

// Write numbers 4-7

void *functionCount2()
{
    for(;;)
    {
       pthread_mutex_lock( &count_mutex );    //     <---- Same mutex

       if( count < COUNT_HALT1 || count > COUNT_HALT2 )
       {
          // Condition of if statement has been met. 
          // Signal to free waiting thread by freeing the mutex.
          // Note: functionCount1() is now permitted to modify "count".
          pthread_cond_signal( &condition_var );
       }
       else
       {
          count++;
          printf("Counter value functionCount2: %d\n",count);
       }

       pthread_mutex_unlock( &count_mutex );

       if(count >= COUNT_DONE) return(NULL);
    }

}

【问题讨论】:

    标签: c multithreading pthreads


    【解决方案1】:

    如果一个线程拥有 锁,那么在另一个人释放它之前,另一个人无法获得它。
    现在如果线程 A 先获得锁,它将阻止线程 B 在关键部分进行,直到锁被释放。


    为什么没有死锁?


    阅读this

    int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
    

    该函数以原子方式释放互斥体并导致调用线程阻塞在条件变量cond上;

    线程 A 将在遇到 cond_wait 时释放锁,并且线程 B 可以继续前进并向条件变量发出信号。

    【讨论】:

    • 你不明白我在问什么。我要求两者都使用相同的互斥锁,如果其中一个拥有授权,另一个必须等​​待进入其互斥锁区域。如果是这样,则在 functionCount1 中,thread1 和 pthread_cond_wait 拥有的互斥锁正在进行中。在这一行是否等待 functionCount2(Thread 2)?或者如果thread2拥有互斥锁,thread1如何增加计数?即使互斥锁已经由 thread2 拥有?
    • @concurrencyboy 立即尝试。我猜让你感到困惑的是线程 A 一旦运行cond_wait 就会释放锁。否则在线程A先获取锁的情况下会死锁。
    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 2013-04-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多