您的位置:首页 > 其它

条件变量

2016-02-14 17:35 183 查看
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

void *thread1(void *arg)
{
pthread_cleanup_push(pthread_mutex_unlock,&mutex);
/*不论是可预见的线程终止还是异常终止,都会存在资源释放的问题,在不考虑因运行出错而退出的前提下,如何保证线程终止时能顺利的释放掉自己所占用的资源,特别是锁资源,就是一个必须考虑解决的问题。最经常出现的情形是资源独占锁的使用:线程为了访问临界资源而为其加上锁,但在访问过程中被外界取消,如果线程处于响应取消状态,且采用异步方式响应,或者在打开独占锁以前的运行路径上存在取消点,则该临界资源将永远处于锁定状态得不到释放。外界取消操作是不可预见的,因此的确需要一个机制来简化用于资源释放的编程。*/
//提供函数回调保护
while (1)
{
printf("thread1 is running\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("thread1 applied the condition\n");
pthread_mutex_unlock(&mutex);
sleep(4);
}
pthread_cleanup_pop(0);

}

void *thread2(void *arg)
{
while (1)
{
printf("thread2 is running\n");
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("thread2 applied the condition\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}

int main()
{
pthread_t thid1, thid2;
printf("condition variable study!\n");
pthread_mutex_init(&mutex, NULL);//注册互斥量
pthread_cond_init(&cond, NULL);//注册条件变量
pthread_create(&thid1, NULL, (void *) thread1, NULL);
pthread_create(&thid2, NULL, (void *) thread2, NULL);

do {
pthread_cond_signal(&cond);
} while (1);

sleep(10);
pthread_exit(0);
return 0;
}


程序运行结果:

condition variable study!
thread2 is running
thread1 is running
thread2 applied the condition
thread1 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread1 is running
thread1 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread1 is running
thread1 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread1 is running
thread1 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread1 is running
thread1 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread1 is running
thread1 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread2 is running
thread2 applied the condition
thread1 is running
thread1 applied the condition
thread2 is running
thread2 applied the condition
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: