该threa_cancel()所使用的线程ID,取消一个特定线程。该函数向线程发送一个取消请求以终止。的语法pthread_cancel()如下 -
int pthread_cancel(pthread_t th);
现在,让我们看看如何使用此函数取消线程。
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <pthread.h> int count = 0; pthread_t sample_thread; void* thread_one_func(void* p) { while (1) { printf("This is thread 1\n"); sleep(1); // 等待 1 秒 count++; if (count == 5) { //如果计数器为 5,则请求取消线程 2 并退出当前线程 pthread_cancel(sample_thread); pthread_exit(NULL); } } } void* thread_two_func(void* p) { sample_thread = pthread_self(); //存储线程 2 的 id while (1) { printf("This is thread 2\n"); sleep(2); // 机智2秒 } } main() { pthread_t t1, t2; //创建两个线程 pthread_create(&t1, NULL, thread_one_func, NULL); pthread_create(&t2, NULL, thread_two_func, NULL); //等待线程完成 pthread_join(t1, NULL); pthread_join(t2, NULL); }输出结果
This is thread 2 This is thread 1 This is thread 1 This is thread 2 This is thread 1 This is thread 1 This is thread 1 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2 This is thread 2