日期:2014-05-16  浏览次数:20712 次

线程清理处理程序小问题

/*********************************************************************************/
/*
线程清理处理程序。
*/
/********************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void cleanup(void *arg)
{
printf("clearup: %s\n", (char *)arg);
}



void * fun(void * arg)
{
printf("in pthread:\n");

//去掉这三句就没错,怎么会在main()函数报错阿???
pthread_cleanup_push(cleanup, (void *)"1");
pthread_cleanup_push(cleanup, (void *)"2");
pthread_cleanup_push(cleanup, (void *)"3");

/*pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
pthread_cleanup_pop(3);
pthread_cleanup_pop(3);
pthread_cleanup_pop(3);*/

pthread_exit((void *)0 );
}


int main()
{
pthread_t tid1;
int err;

if ((err = pthread_create(&tid1, NULL, fun, NULL)) != 0)
{
printf("pthread1 error!\n");
}

pthread_join(tid1, (void * )(0));     //获取传递的参数并等待该子线程结束。

printf("in main pthread:\n");

return 0;
}


运行结果:
[root@localhost work]# gcc 1.c -o 1 -lpthread
1.c: 在函数 ‘fun’ 中:
1.c:38: 错误:expected ‘while’ before ‘int’
1.c:53: 错误:expected declaration or statement at end of input
1.c:53: 错误:expected declaration or statement at end of input
1.c:53: 错误:expected declaration or statement at end of input
1.c:53: 错误:expected declaration or statement at end of input
1.c:53: 错误:expected declaration or statement at end of input
1.c:53: 错误:expected declaration or statement at end of input


我去掉上面的三句就不会报错啊,怎么不去掉在main函数会报错啊????





------解决方案--------------------
http://wenku.baidu.com/view/fd4a162e0066f5335a812191.html
pthread_cleanup_push必须和pthread_cleanup_pop成对出现。