pthread中pthread_cleanup_pop()
#include <iostream>#include <pthread.h>
using namespace std;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int a=0;//被互斥量和条件变量共同保护的数据
void cleanup_handle(void *)
{
pthread_mutex_unlock(&mutex);
}
void *route1(void *)//模拟出队操作的函数 即:a--
{
int oldtype;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);
pthread_cleanup_push(cleanup_handle,NULL);
pthread_mutex_lock(&mutex);
while(a==0)
{
cout<<"Route1 running"<<endl;
pthread_cond_wait(&cond,&mutex);
cout<<"signal_1 is "<<a<<endl;
}
a--;
cout<<"Route1 a is "<<a<<endl;
pthread_mutex_unlock(&mutex);
pthread_cleanup_pop(0); //[Error] second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'
pthread_exit(NULL);
}
void *route2(void *)//模拟入队的操作的函数 即:a++
{
pthread_mutex_lock(&mutex);
while(a==0)
{
cout<<"Route2 running"<<endl;
a++;
pthread_cond_signal(&cond);
cout<<"signal_2 is "<<a<<endl;
}
cout<<"Route2 a is "<<a<<endl;
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main()
{
pthread_t pid1,pid2;
int status=pthread_create(&pid1,NULL,route1,NULL);
if(status)
{
cout<<"Pthread1 create error!"<<endl;
exit(0);
}
status=pthread_create(&pid2,NULL,route2,NULL);
if(status)
{
cout<<"Pthread2 create error!"<<endl;
exit(0);
}
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
return 0;
}