qfedu-linux-advanced-level/day6/thread10.c

38 lines
798 B
C

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
// pthread_cleanup_push() 和 pthread_cleanup_pop()
// 线程清退示例
void *clear_task(void *args);
void *task1(void *data)
{
char *p = malloc(32);
pthread_cleanup_push(clear_task, (void *)p);
strcpy(p, "hello, disen!");
printf("%ld 线程在堆中分配的空间,内容为 %s\n", pthread_self(), p);
pthread_exit(p);
pthread_cleanup_pop(0);
}
void *clear_task(void *args)
{
char *msg = (char *)args;
printf("清退: %s\n", msg);
free(msg);
}
int main()
{
pthread_t tid;
char *q = NULL;
pthread_create(&tid, NULL, task1, NULL);
pthread_join(tid, (void **)&q);
printf("子线程退出结果: %s\n", q);
sleep(2);
return 0;
}