首页 > 后端开发 > C++ > 在C语言中,pthread_cancel()函数的含义是取消一个线程

在C语言中,pthread_cancel()函数的含义是取消一个线程

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
发布: 2023-09-15 10:13:06
转载
1284 人浏览过

在C语言中,pthread_cancel()函数的含义是取消一个线程

The threa_cancel() is used to cancel one particular thread by the thread id. This function sends one cancellation request to the thread for termination. The syntax of the pthread_cancel() is like below −

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</p><p>");
      sleep(1); // wait for 1 seconds
      count++;
      if (count == 5) {
         //if the counter is 5, then request to cancel thread two and exit from current thread
         pthread_cancel(sample_thread);
         pthread_exit(NULL);
      }
   }
}
void* thread_two_func(void* p) {
   sample_thread = pthread_self(); //store the id of thread 2
   while (1) {
      printf("This is thread 2</p><p>");
      sleep(2); // wit for 2 seconds
   }
}
main() {
   pthread_t t1, t2;
   //create two threads
   pthread_create(&t1, NULL, thread_one_func, NULL);
   pthread_create(&t2, NULL, thread_two_func, NULL);
   //wait for completing threads
   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
登录后复制

以上是在C语言中,pthread_cancel()函数的含义是取消一个线程的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
双语言或多语言网站怎么做?
来自于 1970-01-01 08:00:00
0
0
0
C语言计算顺序问题
来自于 1970-01-01 08:00:00
0
0
0
objective-c - iOS9如何设置默认国际化语言
来自于 1970-01-01 08:00:00
0
0
0
Linux下一道C语言的经典面试题
来自于 1970-01-01 08:00:00
0
0
0
linux - 一道C语言printf的经典题目
来自于 1970-01-01 08:00:00
0
0
0
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板