分类: LINUX
2008-08-08 00:49:38
2008-08-07 20:03 线程_终止
线程的终止有三种形式:
/** clean_up_thread.c */
#include
#include
#include
void clean_up(void *arg)
{
printf("clean up: %s\n", (char *)arg);
}
void* thr_fn1(void *arg)
{
pthread_cleanup_push(clean_up, "thread 1 first cleanup progress");
pthread_cleanup_push(clean_up, "thread 1 second cleanup progress"); //用宏实现, 包含“{”, 后面要调用同样数量的pop,否则编译出错
printf("thread 1 push complete\n");
if (arg)
return ((void *)1); //返回终止,不会调用clean up
pthread_cleanup_pop(0); //与pthread_clean_push的个数相对应,因为是用宏实现,包含“}”
pthread_cleanup_pop(0);
return ((void *)1);
}
void* thr_fn2(void *arg)
{
pthread_cleanup_push(clean_up, "thread 2 first cleanup progress");
pthread_cleanup_push(clean_up, "thread 2 second cleanup progress");
printf("thread 2 push complete\n");
if (arg)
pthread_exit((void *)2); //pthread_exit终止,调用clean up
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
pthread_exit((void *)2);
}
void* thr_fn3(void *arg)
{
pthread_cleanup_push(clean_up, "thread 3 first cleanup progress");
pthread_cleanup_push(clean_up, "thread 3 second cleanup progress");
printf("thread 3 push complete\n");
while(1) {
pthread_testcancel(); //外部终止,调用clean up
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return ((void *)1);
}
int main(int argc, char **argv)
{
int err;
pthread_t tid1, tid2, tid3;
void *tret;
err = pthread_create(&tid1, NULL, thr_fn1, (void *)1);
if (err != 0) {
printf("can't create thread 1: %s\n", strerror(err));
return 1;
}
err = pthread_create(&tid2, NULL, thr_fn2, (void *)1);
if (err != 0) {
printf("can't create thread 2: %s\n", strerror(err));
return 1;
}
err = pthread_create(&tid3, NULL, thr_fn3, (void *)1);
if (err != 0) {
printf("can't create thread 3: %s\n", strerror(err));
return 1;
}
err = pthread_join(tid1, &tret);
if (err != 0) {
printf("can't join thread 1: %s\n", strerror(err));
return 1;
}
printf("thread 1 exit code: %d\n", (int)tret);
err = pthread_join(tid2, &tret);
if (err != 0) {
printf("can't join thread 2: %s\n", strerror(err));
return 1;
}
printf("thread 2 exit code: %d\n", (int)tret);
err = pthread_cancel(tid3);
if (err != 0) {
printf("can't cancel thread 3: %s\n", strerror(err));
return 1;
}
err = pthread_join(tid3, &tret);
if (err != 0) {
printf("can't join thread 2: %s\n", strerror(err));
return 1;
}
printf("thread 3 exit code: %d\n", (int)tret);
return 0;
}