您的位置:首页 > 编程语言

POSIX多线程编程-条件变量pthread_cond_t

2012-01-29 14:22 302 查看
       有的时候仅仅依靠锁住共享资源来使用它是不够的。有时候共享资源只有某些状态的时候才能够使用。比方说,某个线程如果要从堆栈中读取数据,那么如果栈中没有数据就必须等待数据被压栈。这种情况下的同步使用互斥锁
是不够的。另一种同步的方式--条件变量,就可以使用在这种情况下。

条件变量的使用总是和互斥锁及共享资源联系在一起的。线程首先锁住互斥锁,然后检验共享资源的状态是否处于可使用的状态。如果不是,那么线程就要等待条件变量。要指向这样的操作就必须在等待的时候将互斥锁解锁,以

便其他线程可以访问共享资源并改变其状态。它还得保证从等到得线程返回时互斥体是被上锁得。当另一个线程改变了共享资源的状态时,它就要通知正在等待条件变量的线程,使之重新变回被互斥锁阻塞的线程。

请看下面的例子:

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

pthread_mutex_t cond_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_var=PTHREAD_COND_INITIALIZER;

void* function_cond1();
void* function_cond2();

int count=0;
#define COUNT_DONE  10
#define COUNT_HALT1  3
#define COUNT_HALT2  6

int main()
{
pthread_t thread1,thread2;
pthread_create(&thread1,NULL,function_cond1,NULL);
pthread_create(&thread2,NULL,function_cond2,NULL);

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

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

void* function_cond1()
{
for(;;)
{
pthread_mutex_lock(&cond_mutex);
pthread_cond_wait(&cond_var,&cond_mutex);
count++;
printf("Counter value functionCount1: %d\n",count);
pthread_mutex_unlock(&cond_mutex);
if(count>=COUNT_DONE) return ;
}
}

void* function_cond2()
{
for(;;)
{
pthread_mutex_lock(&cond_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(&cond_var);
}
else
{
count++;
printf("Counter value functionCount2: %d\n",count);
}
pthread_mutex_unlock(&cond_mutex);
if(count>=COUNT_DONE) return ;
}
}


结果:


 

两个线程同时运行,当在count<COUNT_HALT1||count>COUNT_HALT2的时候,线程1是一直等待的。只有线程2条件到达的时候,调用pthread_cond_signal(&cond_var);通知

线程1,pthread_cond_wait(&cond_var,&cond_mutex);

 

更多文章,欢迎关注:http://blog.csdn.net/wallwind

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息