注册 登录
编程论坛 C语言论坛

pthread中pthread_cleanup_pop()问题

花脸 发布于 2018-06-19 22:32, 1944 次点击

#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);//编译说这行代码出错  208    2    [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(0);
   
}

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(0);
}

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;
}
求各位大佬解释
7 回复
#2
花脸2018-06-20 12:56
???
#3
星泪成寒2018-06-20 15:01
1. 函数定义的参数列表都是错的, void* arg 不能是 void*,2. pthread_cleanup_push 注册一个取消点清理函数, 还没执行到 pthread_exit 你就 pthread_cleanup_pop(0) 给删掉了, cleanup函数不会被调用3. 没看懂你的程序要干啥
#4
花脸2018-06-20 18:45
1.void *和void *arg一样吧。
2.pthread_cond_wait()是一个取消点
3.模拟队列操作route1出队a--,route2进队a++
#5
星泪成寒2018-06-21 09:14
1.定义函数时省略参数名编译不过2.没人调用phtread_cancel(), 谁触发取消 ?
#6
花脸2018-06-21 12:32
回复 5楼 星泪成寒
加上形参编译也没过。。。
#7
星泪成寒2018-06-21 13:18
你所有的函数形参都加全了吗?
#8
花脸2018-06-21 14:18
恩全都加了。
1