Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

POSIX 執行緒清理函數的觸發時機與實作

POSIX 的清理函數(cleanup handler)就像執行緒的「善後機制」,能在特定時機自動執行資源釋放。它的觸發時機主要有三種:

  • 呼叫 pthread_exit() 時,會執行清理函數;但透過 return 正常返回的執行緒「不會」觸發。
  • 當執行緒被其他執行緒取消(cancel)時,會執行。
  • 當 pthread_cleanup_pop() 的參數為非零時,會執行。
#include <stdio.h>
#include <pthread.h>
#include <windows.h>    // Sleep

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

struct Node
{
    int       number;
    struct Node *next;
} *head = NULL;

// 清理函數
void cleanup_handler(void *node)
{
    printf("Cleanup handler of second thread.\n");
    free(node);
    pthread_mutex_unlock(&mtx);
}

void* thread_func(void *arg)
{
    struct Node *p = NULL;
    // 清理函數入棧,此 demo 只需一個清理函數
    pthread_cleanup_push(cleanup_handler, p);

    while (true)
    {
        pthread_mutex_lock(&mtx);
        if (head == NULL)
        {
            pthread_cond_wait(&cond, &mtx);
        }
        p = head;
        head = head->next;
        printf("Got %d from front of queue\n", p->number);
        free(p);
        pthread_mutex_unlock(&mtx);
    }
    /* 若從此處終止執行緒,則屬於正常退出,無需清理。所以,只需將清理函數出棧。故而用
       參數零。若是從上面的「取消點」退出,則清理函數出棧時被調用:鎖被打開,同時釋放資源。*/
    pthread_cleanup_pop(0);
    return 0;
}

int main(int argc, char* argv[])
{
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    for (int i = 0; i < 10; i++)
    {
        struct Node* p = (Node *)malloc(sizeof(struct Node));
        p->number = i;

        // 對 head 操作屬於臨界區
        pthread_mutex_lock(&mtx);
        p->next = head;
        head = p;
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mtx);
        // 所以要用互斥鎖保護起來--!

        Sleep(1);
    }
    printf("Main thread wants to cancel the 2nd thread.\n");

    /* 關於 pthread_cancel,有一點額外的說明,它是從外部終止子執行緒,子執行緒會在
       最近的取消點,退出執行緒。而在我們的程式碼裡,最近的取消點是 pthread_cond_wait() 了。*/
    pthread_cancel(tid);
    pthread_join(tid, NULL);
    printf("All done -- exiting\n");
    return 0;
}

push 與 pop 的配對藝術

清理函數透過 pthread_cleanup_push 入棧,。pthread_cleanup_pop 出棧。本例刻意讓 pop 帶入參數 0:因為執行緒若從 while 迴圈「正常」離開,屬常規退出,不需要清理,只需安靜地把 handler 出棧即可;但若執行緒是在 pthread_cond_wait() 這個取消點被外部 pthread_cancel 打斷,。pop 出棧時就會真正執行清理函數——解開互斥鎖、釋放資源,避免留下死鎖與記憶體洩漏。這正是清理機制在「異常終止」情境下的價值所在。

Copyright © Linux教程網 All Rights Reserved