51 lines
909 B
C
51 lines
909 B
C
#include <stdio.h>
|
|
#include <pthread.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
|
|
// pthread_cancel 示例
|
|
int isCancel = 0;
|
|
|
|
void *show(void *data)
|
|
{
|
|
for (int i = 0; i < 100; i++)
|
|
{
|
|
printf("线程(%ld): i=%d\n", pthread_self(), i);
|
|
sleep(1);
|
|
if (isCancel)
|
|
{
|
|
printf("%ld 被取消\n", pthread_self());
|
|
break;
|
|
|
|
// pthread_cancel(pthread_self()); // 取消线程
|
|
}
|
|
}
|
|
pthread_exit(NULL);
|
|
}
|
|
|
|
void *watch_task(void *data)
|
|
{
|
|
while (1)
|
|
{
|
|
char n = getchar();
|
|
if (n == '1')
|
|
{
|
|
isCancel = 1;
|
|
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, NULL);
|
|
|
|
pthread_join(tid, NULL);
|
|
pthread_join(tid2, NULL);
|
|
|
|
return 0;
|
|
}
|