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

用 C 語言做物件導向:一個可掛起/恢復的線程封裝

C 沒有 class,但靠結構體加函式指標,一樣能做出物件導向的封裝。以下示範一個支援啟動、等待、取消、退出、掛起與恢復的 pthread 包裝。

mythr.h

/*
 * 線程封裝演示 - C 版本 mythr.h
 */
#ifndef MYTHR_H
#define MYTHR_H
#include <pthread.h>

typedef unsigned int bool;
#define true  1
#define false 0

typedef void (*RUN)(void *arg);

typedef struct __mythr {
    RUN      run;         /* 線程工作函數 */
    void    *arg;         /* 傳給 run 的參數 */
    bool     bthrun;      /* 循環標志 */
    bool     bthrsusend;  /* 掛起標志 */

    /* private */
    pthread_t     tid;
    pthread_mutex_t mutex;
    pthread_cond_t  cont;
} MYTHR, *PMYTHR;

int  thr_start(PMYTHR pthr);     /* 開啟 */
int  thr_wait(PMYTHR pthr);      /* 等待 */
int  thr_cancel(PMYTHR pthr);    /* 取消 */
void thr_exit(PMYTHR pthr);      /* 退出 */
void thr_suspend(PMYTHR pthr);   /* 掛起 */
void thr_resume(PMYTHR pthr);    /* 恢復 */
#endif

公開欄位只有工作函式、參數與兩個旗標,pthread 的 mutex、cond、tid 都藏在「private」註解之後——這就是 C 版的封裝。

mythr.c

#include <stdio.h>
#include <stdlib.h>
#include "mythr.h"

static void *routine(void *arg)
{
    PMYTHR pthr = (PMYTHR)arg;
    pthread_mutex_init(&pthr->mutex, NULL);
    pthread_cond_init(&pthr->cont, NULL);
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    do {
        pthread_mutex_lock(&pthr->mutex);
        if (pthr->bthrsusend) {
            if (0 != pthread_cond_wait(&pthr->cont, &pthr->mutex)) {
                perror("work:pthread_cond_wait");
                return (void *)-1;
            }
        }
        pthread_mutex_unlock(&pthr->mutex);
        pthr->run(pthr->arg);
    } while (pthr->bthrun);

    pthread_cond_destroy(&pthr->cont);
    pthread_mutex_destroy(&pthr->mutex);
    return (void *)0;
}

int thr_start(PMYTHR pthr)
{
    if (NULL != pthr->run) {
        return pthread_create(&pthr->tid, NULL, routine, (void *)pthr);
    }
    return -1;
}

int thr_wait(PMYTHR pthr)
{
    if (NULL != pthr->run) {
        return pthread_join(pthr->tid, NULL);
    }
    return -1;
}

int thr_cancel(PMYTHR pthr)
{
    if (NULL != pthr->run) {
        pthread_cancel(pthr->tid);
        pthread_cond_destroy(&pthr->cont);
        pthread_mutex_destroy(&pthr->mutex);
        return 0;
    }
    return -1;
}

void thr_exit(PMYTHR pthr)
{
    if (NULL != pthr->run) {
        pthread_mutex_lock(&pthr->mutex);
        if (pthr->bthrsusend) {
            pthr->bthrsusend = false;
            pthread_cond_signal(&pthr->cont);
        }
        pthr->bthrun = false;
        pthread_mutex_unlock(&pthr->mutex);
    }
}

void thr_suspend(PMYTHR pthr)
{
    pthread_mutex_lock(&pthr->mutex);
    if (!pthr->bthrsusend) {
        pthr->bthrsusend = true;
    }
    pthread_mutex_unlock(&pthr->mutex);
}

void thr_resume(PMYTHR pthr)
{
    pthread_mutex_lock(&pthr->mutex);
    if (pthr->bthrsusend) {
        pthr->bthrsusend = false;
        pthread_cond_signal(&pthr->cont);
    }
    pthread_mutex_unlock(&pthr->mutex);
}

測試程式

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "mythr.h"

unsigned int k = 0;

void thrfunc(void *arg)
{
    printf("Thr---%s---%u\r\n", (char *)arg, k++);
    sleep(1);
}

MYTHR thr = {
    .run       = thrfunc,
    .arg       = "test",
    .bthrun    = true,
    .bthrsusend = true,
};

int main(int argc, char **argv)
{
    thr_start(&thr);

    while (1) {
        printf("Please Input:\r\n");
        char ch = getchar();

        switch (ch) {
        case 's': case 'S': thr_suspend(&thr); break;
        case 'r': case 'R': thr_resume(&thr);  break;
        case 'c': case 'C': thr_cancel(&thr);  goto EXIT_STEP;
        case 'e': case 'E': thr_exit(&thr);    goto EXIT_STEP;
        case 'q': case 'Q': exit(1);
        };
    }
EXIT_STEP:
    thr_wait(&thr);
    printf("---done---\r\n");
    return 0;
}

設計上的關鍵是「掛起」用條件變數實作:工作函式每跑一輪前先檢查 bthrsusend,為真就 pthread_cond_wait 睡下去,直到 thr_resume 發出信號。這樣就不必用忙等去實作用戶態的排程。若要更嚴謹,thr_cancel 裡的 mutex/cond 銷毀應與工作線程協調,避免銷毀時仍有人在 wait。

Copyright © Linux教程網 All Rights Reserved