溫馨提示×

如何終止pthread_create創建的線程

小樊
148
2024-12-28 23:15:12
欄目: 編程語言

要終止一個通過pthread_create創建的線程,您可以使用以下方法之一:

  1. 線程自動結束:當線程的函數執行完畢時,線程會自動結束。確保您的線程函數在邏輯上有一個明確的退出條件。

  2. 使用全局標志變量:創建一個全局布爾變量(例如thread_exit),并在需要終止線程時將其設置為true。在線程的主函數中,定期檢查此標志,并在適當的時候使用pthread_exit()函數結束線程。

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

pthread_mutex_t lock;
pthread_cond_t finish_cond;
int thread_exit = false;

void* thread_function(void *arg) {
    while (!thread_exit) {
        // 執行線程任務
    }
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&finish_cond, NULL);

    pthread_create(&thread, NULL, thread_function, NULL);

    // 讓線程執行一段時間
    sleep(5);

    // 終止線程
    pthread_mutex_lock(&lock);
    thread_exit = true;
    pthread_cond_signal(&finish_cond);
    pthread_mutex_unlock(&lock);

    // 等待線程結束
    pthread_join(thread, NULL);

    pthread_cond_destroy(&finish_cond);
    pthread_mutex_destroy(&lock);

    return 0;
}
  1. 使用pthread_cancel()函數:pthread_cancel()函數會向線程發送一個取消請求,線程需要檢查是否允許被取消。如果允許被取消,線程將執行取消處理代碼,然后結束。要使用此方法,您需要在線程函數中實現取消處理代碼。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void* thread_function(void *arg) {
    while (1) {
        // 執行線程任務
    }
    return NULL;
}

int main() {
    pthread_t thread;

    pthread_create(&thread, NULL, thread_function, NULL);

    // 讓線程執行一段時間
    sleep(5);

    // 終止線程
    pthread_cancel(thread);

    // 等待線程結束
    pthread_join(thread, NULL);

    return 0;
}

請注意,使用pthread_cancel()可能導致資源泄漏,因為線程可能沒有機會釋放其占有的資源。因此,在使用pthread_cancel()之前,請確保線程能夠安全地結束。在許多情況下,使用全局標志變量或自動結束的方法更為可靠。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女