#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
using namespace std;
pthread_cond_t taxiarrive = PTHREAD_COND_INITIALIZER;
//int pci = pthread_cond_init(&taxiarrive,NULL);
pthread_mutex_t menarrive = PTHREAD_MUTEX_INITIALIZER;
//int pmi = pthread_mutex_init(&menarrive,NULL);
int mencount = 0;
void* taxicome(void* name){
cout<<"taxi: "<<(char*)name<<"arrived"<<endl;
while(1){
pthread_mutex_lock(&menarrive);
if(mencount > 0){
pthread_cond_signal(&taxiarrive);
pthread_mutex_unlock(&menarrive);}
pthread_mutex_unlock(&menarrive);}
pthread_exit((void*)0);}
void* mencome(void* name){
cout<<(char*)name<<" come,need a taxi!"<<endl;
pthread_mutex_lock(&menarrive);
mencount++;
pthread_cond_wait(&taxiarrive,&menarrive);
pthread_mutex_unlock(&menarrive);
cout<<(char*)name<<" now get a taxi!"<<endl;
pthread_exit((void*)0);}
int main(){
pthread_t tid[3];
int iret = 0;
iret = pthread_create(&tid[0],NULL,taxicome,(void*)(" JACK "));
if(iret){
cout<<"线程1创建失败"<<endl;
return iret;}
cout<<"time passing by "<<endl;
sleep(1);
iret = pthread_create(&tid[1],NULL,mencome,(void*)(" JANE "));
if(iret){
cout<<"线程2创建失败"<<endl;
return iret;}
cout<<"time passing by "<<endl;
sleep(1);
iret = pthread_create(&tid[2],NULL,taxicome,(void*)(" TOM "));
if(iret){
cout<<"线程3创建失败"<<endl;
return iret;}
cout<<"time passing by "<<endl;
sleep(1);
void* retval;
for(int i = 0;i<3;i++){
iret = pthread_join(tid[i],&retval);
if(iret){
cout<<"线程退出异常"<<endl;
return iret;}
cout<<"retval="<<(long)retval<<endl;}
return 0;}
运行结果:
time passing by taxi: JACK arrived
time passing by
JANE come,need a taxi!
JANE now get a taxi!
time passing by
taxi: TOM arrived
p5: ../nptl/pthread_mutex_lock.c:81: __pthread_mutex_lock: Assertion `mutex->__data.__owner == 0' failed.
已放弃 (核心已转储)
.......