卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章20273本站已运行347

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

<?xml encoding="utf-8" ?>

在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>");
      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);
}</p>

输出

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
卓越飞翔博客
上一篇: 了解PHP Late静态绑定的实现方式及其优势
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏