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

45 lines
923 B
C
Raw Normal View History

2023-08-21 19:45:29 +08:00
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
// pthread_cancel 示例 2
void *show(void *data)
{
for (int i = 0; i < 100; i++)
{
printf("线程(%ld): i=%d\n", pthread_self(), i);
sleep(1);
}
pthread_exit(NULL);
}
void *watch_task(void *data)
{
pthread_t brother_th = *((pthread_t *)data);
while (1)
{
char n = getchar();
if (n == '1')
{
printf("取消兄弟 %ld 线程\n", brother_th);
pthread_cancel(brother_th); // 根据传入的兄弟线程号取消兄弟线程
break;
}
}
return NULL;
}
int main(int argc, char const *argv[])
{
pthread_t tid, tid2;
pthread_create(&tid, NULL, show, NULL);
pthread_create(&tid2, NULL, watch_task, &tid); // 将兄弟线程号传递过去
pthread_join(tid, NULL);
pthread_join(tid2, NULL);
return 0;
}