c - Pthread 条件变量和无死锁

标签 c multithreading pthreads

我在看题目的时候,找到了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);
    }

}

最佳答案

如果一个线程拥有 锁,那么在另一个释放它之前,另一个不能获取它。
现在,如果线程 A 先获得锁,它将阻止线程 B 进入临界区,直到锁被释放。


为什么没有死锁?


阅读this :

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

This function atomically releases the mutex and cause the calling thread to block on the condition variable cond;

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

关于c - Pthread 条件变量和无死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45627497/

相关文章:

android - 如何提高android中的OpenCV人脸检测性能?

javascript - 如何正确地在node.js中使数据库流动

c++ - C++线程加入后不会中止

c - 在 pthread_mutex_init 之前调用 pthread_mutex_lock 是否安全?

c - 使用深度优先搜索找到具有最大值(value)的路径

c - 如何用C下载网页

c - C 中带有 char 数组的未定义行为(?)

java - 可扩展优先级ThreadPoolExecutor

c - 如何多线程我的函数?使用 pthread

pthreads - 设计一个仅在没有可能的死锁的情况下提供锁的类