C 语言的 pthread_cancel()


threa_cancel() 用于通过线程 ID 取消特定线程。此函数向线程发送一个终止请求。pthread_cancel() 的语法如下 −

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
");       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
");       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

更新于: 2019 年 7 月 30 日

622 次浏览

启动你的 职业生涯

完成课程可获得认证

开始学习
广告