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

49 lines
891 B
C
Raw Normal View History

2023-08-21 19:45:29 +08:00
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *task1(void *data)
{
for (int i = 0; i < 10; i++)
{
printf("%ld 子线程执行了 %d 次\n", pthread_self(), i + 1);
sleep(1);
}
return NULL;
}
void *task2(void *data)
{
for (int i = 0; i < 100; i++)
{
if (i % 2 == 0)
printf("%ld 子线程, 偶数 %d 次\n", pthread_self(), i);
sleep(1);
}
return NULL;
}
void *clear(void *args)
{
char *msg = (char *)args;
printf("清退: %s\n", msg);
}
int main()
{
pthread_t tid, tid2;
pthread_create(&tid, NULL, task1, NULL);
pthread_create(&tid2, NULL, task2, NULL);
pthread_cleanup_push(clear, "task1");
pthread_cleanup_push(clear, "task2");
pthread_join(tid2, NULL);
pthread_cleanup_pop(1);
pthread_join(tid, NULL);
pthread_cleanup_pop(1);
return 0;
}