温馨提示×

C语言 pthread_cancel()实例讲解

小亿
91
2023-12-18 15:22:27
栏目: 编程语言

pthread_cancel()函数用于取消一个线程。它发送一个取消请求给指定的线程,并不是立即终止该线程,而是在目标线程下一个取消点时终止。取消点是线程在其中可以安全地取消的位置。线程可以通过调用pthread_setcancelstate()函数设置是否接受取消请求,以及通过调用pthread_setcanceltype()函数设置取消的类型。

下面是一个使用pthread_cancel()函数的简单示例:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void* thread_function(void* arg) {
    printf("Thread is running\n");
    
    // 设置取消点
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
    
    // 循环执行一些任务
    while (1) {
        // 检查是否有取消请求
        pthread_testcancel();
        
        // 执行一些任务
        printf("Performing task...\n");
    }
    
    printf("Thread is exiting\n");
    pthread_exit(NULL);
}

int main() {
    pthread_t thread;
    
    // 创建线程
    if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
        fprintf(stderr, "Failed to create thread\n");
        return 1;
    }
    
    // 等待一段时间
    sleep(2);
    
    // 取消线程
    if (pthread_cancel(thread) != 0) {
        fprintf(stderr, "Failed to cancel thread\n");
        return 1;
    }
    
    // 等待线程结束
    if (pthread_join(thread, NULL) != 0) {
        fprintf(stderr, "Failed to join thread\n");
        return 1;
    }
    
    printf("Thread has been canceled\n");
    
    return 0;
}

在上面的代码中,我们首先创建了一个新的线程,然后等待2秒,最后使用pthread_cancel()函数取消该线程。取消请求会在线程的取消点处生效,同时线程会执行清理函数。在本例中,取消点是通过调用pthread_testcancel()函数实现的,当检测到有取消请求时,该函数会立即取消线程执行,并执行相应的清理动作。

注意,pthread_cancel()函数并不是强制终止线程的方法,它只是向目标线程发送一个取消请求。目标线程可以选择是否接受取消请求,并通过设置取消点来确定在何时响应取消请求。此外,如果目标线程正在执行一些不可取消的操作,取消请求可能会被延迟,直到取消点时才生效。

综上所述,pthread_cancel()函数用于向指定线程发送取消请求,在线程的下一个取消点时终止线程的执行。通过设置取消点,线程可以选择在何时响应取消请求。

0