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