qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

Linux线程同步之条件变量

  条件变量是线程可用的另一种同步机制。条件变量给多个线程提供了一个会合的场所。条件本身是由互斥量保护的。线程在改变 条件状态前必须首先锁住互斥量。
  条件变量的初始化 pthread_cond_init
  去除初始化 pthread_cond_destroy
  等待 pthread_cond_wait
  满足条件给向进程发送信号 pthread_cond_signal
  下面程序展示了利用条件变量等待另外两个线程满足条件时,第三个进程继续向前执行
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
pthread_mutex_t m1, m2;
pthread_cond_t c1,c2;
pthread_t t1, t2, t3;
void* r1(void *arg)
{
sleep(10); //睡眠10秒
pthread_cond_signal(&c1);
printf("t1 finish\n");
while(1);
}
void* r2(void *arg)
{
sleep(15);//睡眠15秒
pthread_cond_signal(&c2);
printf("t2 finish\n");
while(1);
}
void* r3(void *arg)
{
pthread_cond_wait(&c1, &m1);
pthread_cond_wait(&c2, &m2);
printf("finish\n");//15秒后线程打印
}
main()
{
pthread_mutex_init(&m1, 0);
pthread_mutex_init(&m2, 0);
pthread_cond_init(&c1, 0);
pthread_cond_init(&c2, 0);
pthread_create(&t1, 0, r1, 0);
pthread_create(&t2, 0, r2, 0);
pthread_create(&t3, 0, r3, 0);
while(1);
}


  执行结果
  条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
  下面程序中,由于在互斥量中等待条件会造成死锁
#include <pthread.h>
#include <stdio.h>
#include <signal.h>
pthread_t t1,t2;
pthread_mutex_t m1,m2;
pthread_cond_t c;
void *r1(void *d)
{
while(1)
{
pthread_mutex_lock(&m1);
printf("wait\n");
pthread_cond_wait(&c,&m2);
pthread_mutex_unlock(&m1);
}
}
void *r2(void *d)
{
while(1)
{
pthread_mutex_lock(&m1);
printf("signal\n");
pthread_cond_signal(&c);
pthread_mutex_unlock(&m1);
}
}
main()
{
pthread_cond_init(&c,0);
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_create(&t1,0,r1,0);
pthread_create(&t2,0,r2,0);
while(1);
/*
pthread_join(t1,0);
pthread_join(t2,0);
pthread_mutex_destroy(&m2);
pthread_mutex_destroy(&m1);
pthread_cond_destroy(&c);*/
}
  执行结果,程序执行到某一时刻发生死锁,不再向下执行
  改进后的程序,允许线程以无竞争的方式等待,不会发生死锁
#include <pthread.h>
#include <stdio.h>
#include <signal.h>
pthread_t t1,t2;
pthread_mutex_t m1,m2;
pthread_cond_t c;
void *r1(void *d)
{
while(1)
{
pthread_mutex_lock(&m1);
printf("wait\n");
pthread_cond_wait(&c,&m1);
pthread_mutex_unlock(&m1);
}
}
void *r2(void *d)
{
while(1)
{
pthread_mutex_lock(&m1);
printf("signal\n");
pthread_cond_signal(&c);
pthread_mutex_unlock(&m1);
}
}
main()
{
pthread_cond_init(&c,0);
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_create(&t1,0,r1,0);
pthread_create(&t2,0,r2,0);
while(1);
/*
pthread_join(t1,0);
pthread_join(t2,0);
pthread_mutex_destroy(&m2);
pthread_mutex_destroy(&m1);
pthread_cond_destroy(&c);*/
}

posted on 2014-02-28 11:01 顺其自然EVO 阅读(372) 评论(0)  编辑  收藏 所属分类: linux


只有注册用户登录后才能发表评论。


网站导航:
 
<2014年2月>
2627282930311
2345678
9101112131415
16171819202122
2324252627281
2345678

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜