/*
* main.cpp
*
* Created on: Jul 3, 2014
* Author: john
*/
#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;
//声明互斥锁和条件变量
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread1(void* arg)
{
while(1)
{
cout<<"thread1 is running\n";
//pthread_mutex_lock是成功枷锁之后返回,如果已经被锁朱,则该执行被阻塞
pthread_mutex_lock(&mutex );
//基于条件变量阻塞,无条件等待,或者是计时等待pthread_cond_timewait
pthread_cond_wait(&cond,&mutex);
cout<<"thread1 applied the condition\n";
//pthread_mutex_unlock操作需要满足两个条件,一个是必须保证该锁是被锁住状态,二是解锁线程必须是枷锁的线程
pthread_mutex_unlock(&mutex);
sleep(4);
}
}
void * thread2(void*arg)
{
while(1)
{
cout<<"thread2 is running\n";
pthread_mutex_lock(&mutex);
//基于条件变量阻塞,无条件等待,或者是计时等待pthread_cond_timewait
pthread_cond_wait(&cond,&mutex) ;
cout<<"thread2 applied the condition\n";
pthread_mutex_unlock(&mutex);
sleep(4);
}
}
int main()
{
pthread_t td1,td2;
cout<<"condition variable study\n";
//pthread_mutex_t互斥变量只有在init初始化之后才能使用
pthread_mutex_init(&mutex,NULL);
//条件变量的初始化操作
pthread_cond_init(&cond,NULL);
pthread_create(&td1,NULL,thread1,NULL);
pthread_create(&td2,NULL,thread2,NULL);
do
{
//激活一个等待条件成立的线程
pthread_cond_signal(&cond);
} while(1);
sleep(50);
//互斥变量使用完成之后必须进行destroy操作
pthread_mutex_destroy(&mutex);
//条件变量使用完成之后进行destroy操作
pthread_cond_destroy(&cond);
pthread_exit(0);
}
互斥变量的使用需要注意以下几点
1.互斥变量使用之前必须要进行初始化 pthread_mutex_init
2.pthread_mutex_lock操作之前该互斥变量已经上锁,则阻塞
3.pthread_mutex_trylock,.尝试枷锁,失败,则立即返回
4.pthread_mutex_unlock操作的锁必须是已经lock的互斥变量,同时该解锁线程也必须是枷锁的线程
5.使用完成之后使用pthread_mutex_destroy
条件变量的使用需要注意以下几点
1.条件标量使用之前必须pthread_cond_init操作
2.pthread_cond_wait无条件等待条件变量的激活
3.pthread_conf_timedwait阻塞直到条件变量激活,或者到时间
4.pthread_cond_signal解除特定线程的阻塞(在多个线程等待条件变量激活的队列中选择),或者说,条件变量的激活
5.pthread_cond_broadcast解除所有线程的阻塞,整个等待条件变量激活的队列都会得到条件变量激活的通知,立即向下执行