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
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法