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 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下