溫馨提示×

C語言 pthread_cancel()實例講解

小億
220
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女