当我查看主题时,我找到了来自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);
}
}
答案 0 :(得分:0)
如果一个主题拥有
锁定,然后另一个人在另一个人释放它之前无法获得它。
现在,如果线程A首先获得锁定,它将阻止线程B
在关键部分进展,直到锁定被释放。
为什么没有死锁?
阅读this:
firstname = obj.employees[1][fn]
lastname = obj.employees[1][ln]
此函数以原子方式释放互斥锁并导致调用线程阻塞条件变量cond;
线程A会在命中int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
时释放锁定,线程B可以进行并发出条件变量信号。