C 中的 pthread_cancel()
该threa_cancel()所使用的线程ID,取消一个特定线程。该函数向线程发送一个取消请求以终止。的语法pthread_cancel()如下-
int pthread_cancel(pthread_t th);
现在,让我们看看如何使用此函数取消线程。
示例
#include输出结果#include #include #include 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