对于多线程程序来说,同步是指在一定的时间内只允许某一个线程访问某个资源 。 而在
此时间内,不允许其他的线程访问该资源。同步资源的方式:互斥锁、条件变量、读写锁、
信号量。
条件变量的理念:当线程在等待满足某些条件时使线程进入睡眠状态,一旦条件满足,就唤
醒因等待满足特定条件而睡眠的线程
条件变量(条件锁)也可以解决线程同步和共享资源访问的问题,条件变量是对互斥锁的补充,它允许一个线程阻塞并等待另一个线程发送的信号,当收到信号时,阻塞的线程被唤醒并试图锁定与之相关的互斥锁。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <iostream>
#include <pthread.h>
using namespace std;
/*提示出租车到达的条件变量*/
pthread_cond_t taxiCond = PTHREAD_COND_INITIALIZER;
/*同步锁*/
pthread_mutex_t taxiMutex = PTHREAD_MUTEX_INITIALIZER;
int travelerCound=0;
void * traveler_arrive(void * name)
{
cout<<"Traveler: "<<(char *)name<<" needs a taxi now!"<<endl;
pthread_mutex_lock(&taxiMutex);
travelerCound++;
pthread_cond_wait(&taxiCond,&taxiMutex);
pthread_mutex_unlock(&taxiMutex);
cout<<"Traveler: "<<(char *)name<<" now got a taxi!"<<endl;
pthread_exit((void*)0);
}
void * taxi_arrive(void * name)
{
cout<<"Taxi: "<<(char *)name<<" arrives."<<endl;
sleep(3);
while(1)
{
pthread_mutex_lock(&taxiMutex);
if(travelerCound>0)
{
pthread_cond_signal(&taxiCond);
pthread_mutex_unlock(&taxiMutex);
cout<<"Taxi: "<<(char *)name<<" Got a traveler."<<endl;
travelerCound--;
break;
}
else
{
cout<<"Taxi: "<<(char *)name<<" Left."<<endl;
pthread_exit((void*)0);
}
pthread_mutex_unlock(&taxiMutex);
}
pthread_exit((void*)0);
}
int main(){
pthread_t tids[3];
int iRet = pthread_create(&tids[0],NULL,taxi_arrive,(void*)(" Jack "));
if(iRet)
{
printf("pthread_create error: iRet=%d\n",iRet);
return iRet;
}
printf("Time passing by.\n");
sleep(1);
iRet = pthread_create(&tids[1],NULL,traveler_arrive,(void*)(" Susan "));
if(iRet)
{
printf("pthread_create error: iRet=%d\n",iRet);
return iRet;
}
printf("Time passing by.\n");
sleep(1);
iRet = pthread_create(&tids[2],NULL,taxi_arrive,(void*)(" Mike "));
if(iRet)
{
printf("pthread_create error: iRet=%d\n",iRet);
return iRet;
}
printf("Time passing by.\n");
sleep(1);
void *retval;
for(int i=0;i<3;i++)
{
iRet=pthread_join(tids[i],&retval);
if (iRet)
{
printf("pthread_join error: iRet=%d\n",iRet);
return iRet;
}
printf("retval=%ld\n",(long)retval);
}
return 0;
}