Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Linux 多線程編程詳解:pthread 建立、同步、屬性與取消

本文整理自《Linux 程序設計·第 3 版》、《Linux 環境 C 程序設計》、《C 語言核心技術》與《深入理解計算機系統·第 2 版》等書,範例運行環境為 Linux 3.10 核心搭配 GCC 4.8.2。

1. 進程與線程

Linux 建立新線程時,該線程擁有自己的堆疊(因為區域變數屬於它自己),但與建立者共享全域變數、檔案描述子、信號處理器與當前工作目錄狀態。

這與 fork 有本質差異:fork 會複製出子進程,子進程擁有自己的變數與 PID,排程獨立,幾乎完全不受父進程影響。可以說,進程是資源分配的基本單位,而線程是排程的基本單位,同一進程內的線程共享進程取得的時間切片。

2. _REENTRANT 巨集

多線程程式中,預設只有一個 errno 供所有線程共享。當某線程準備讀取剛才的錯誤碼時,很可能已被另一線程的函式呼叫改掉;fputs 這類使用獨立全域緩衝區的快取函式也有類似問題。

解法是使用可重入的例程。只要在程式中定義 _REENTRANT(且必須放在所有 #include 之前),編譯器就會:

  • 為部分函式改用可安全重入的版本,通常是在名稱後加 _r(如 foo 變 foo_r);
  • 把 stdio.h 中以巨集實作的函式轉為可重入版本;
  • 讓 errno 變成一次函式呼叫,以多線程安全的方式取得真正的錯誤碼。

3. 線程基本函式

多數 pthread_xxx 函式失敗時並不遵循 UNIX 慣例回傳 -1,而是回傳錯誤碼;成功則回傳 0。

3.1 建立線程

#include <pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t *attr,
                   void *(*start_routine)(void *), void *arg);
  • thread:指向 pthread_t 的指標,用來引用新線程(pthread_t 一般定義為 unsigned long)。
  • attr:線程屬性,無特殊需求時填 NULL。
  • start_routine:新線程要執行的函式位址,參數與回傳值皆為 void *。
  • arg:傳給該函式的參數。

3.2 線程終止

void pthread_exit(void *retval);

retval 指向線程想回傳的物件。注意:絕對不要回傳指向區域變數的指標,因為呼叫之後該變數已不存在。

3.3 回收線程

int pthread_join(pthread_t th, void **thread_return);

以阻塞方式等待 th 指定的線程結束,函式返回時該線程資源被回收;若線程已結束則立即返回。被等待的線程必須是 joinable 的。

一個基礎範例(thread1.c):

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

void *thread_function(void *arg);
char message[] = "Hello World!";

int main()
{
    int res;
    pthread_t a_thread;
    void *thread_result;

    res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
    if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); }

    printf("Waiting for thread to finish...\n");
    res = pthread_join(a_thread, &thread_result);
    if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); }

    printf("Thread joined, it returned: %s\n", (char *)thread_result);
    printf("Message is now: %s\n", message);
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg)
{
    printf("thread_function() is running. Argument is: %s\n", (char *)arg);
    sleep(3);
    strcpy(message, "Bye!");
    pthread_exit("Thank you for your CPU time!");
}

編譯與運行:

gcc -D _REENTRANT thread1.c -o thread1 -lpthread
./thread1

輸出:

Waiting for thread to finish...
thread_function() is running. Argument is: Hello World!
Thread joined, it returned: Thank you for your CPU time!
Message is now: Bye!

值得細看的是:因為 pthread_exit 回傳的是指標,所以 pthread_join 的第二個參數是二級指標。另外,新線程改寫了 message 而主線程也看得到——若改用 fork,子進程會複製一份,兩邊互不相干。

4. 線程並發

下面用輪詢(忙等待)示範兩個線程同時執行,thread2.c:

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

int flag = 1;                     /* 進程內所有線程共享 */
void *thread_function(void *arg);

int main()
{
    int res, count = 1;
    pthread_t a_thread;

    res = pthread_create(&a_thread, NULL, thread_function, NULL);
    if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); }

    while (count++ <= 10) {
        if (flag == 1) { printf("1"); flag = 2; }
        else sleep(1);
    }
    printf("\nWaiting for thread to finish...\n");
    pthread_join(a_thread, NULL);
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg)
{
    int count = 1;                /* 區域變數不共享 */
    while (count++ <= 10) {
        if (flag == 2) { printf("2"); flag = 1; }
        else sleep(1);
    }
}
gcc -D _REENTRANT thread2.c -o thread2 -lpthread
./thread2
# 1212121212
# Waiting for thread to finish...

忙等待顯然笨拙且耗 CPU,接著看更好的同步機制。

5. 線程同步

5.1 信號量

#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_post(sem_t *sem);      /* 原子地 +1,釋放信號量 */
int sem_wait(sem_t *sem);      /* 原子地 -1,值為 0 時等待 */
int sem_destroy(sem_t *sem);

pshared 為 0 表示進程內局部信號量,非 0 則可跨進程共享;value 是初始值。若要清理的信號量仍有線程在等待,sem_destroy 會回報錯誤。

範例(thread3.c):主線程輸入字串,子線程統計每行字元數,輸入 end 結束。

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

#define SIZE 1024
char buffer[SIZE] = {0};
sem_t sem;

void *thread_function(void *arg)
{
    sem_wait(&sem);
    while (strncmp("end", buffer, 3) != 0) {
        printf("You input %d characters\n", (int)strlen(buffer));
        sem_wait(&sem);
    }
    pthread_exit(NULL);
}

int main()
{
    int res;
    pthread_t a_thread;

    sem_init(&sem, 0, 0);
    res = pthread_create(&a_thread, NULL, thread_function, NULL);
    if (res != 0) { perror("Thread create failed"); exit(EXIT_FAILURE); }

    printf("Input some text, Enter 'end' to finish:\n");
    while (scanf("%s", buffer)) {
        sem_post(&sem);
        if (strncmp("end", buffer, 3) == 0) break;
    }
    pthread_join(a_thread, NULL);
    sem_destroy(&sem);
    exit(EXIT_SUCCESS);
}
gcc -D _REENTRANT thread3.c -o thread3 -lpthread

5.2 互斥量

#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
                       const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

關於 restrict:它只用於限定指標,告知編譯器「所有修改該指標所指內容的動作都 ONLY 透過該指標進行」,因此不存在其他修改路徑,編譯器便能做更積極的最佳化。例如 memcpy(void *restrict dest, const void *restrict src, size_t n) 因兩參數皆加 restrict,兩塊區域不得重疊;相對地 memmove 允許重疊。

這些函式成功回傳 0,失敗回傳錯誤碼,但不設定 errno,所以務必檢查回傳值。屬性設定此處從略,直接填 NULL。用互斥量改寫 thread3.c 即得 thread4.c,運行結果相同:

gcc -D _REENTRANT thread4.c -o thread4 -lpthread

6. 線程屬性

有些場合我們並不需要 pthread_join。例如主線程是服務線程、第二個線程負責資料備份,備份完畢後它可以直接退出,不必回到主線程——這就是「脫離線程」(detached)。常用屬性函式:

int pthread_attr_init(pthread_attr_t *attr);                     /* 初始化屬性 */
int pthread_attr_setscope(pthread_attr_t *attr, int scope);
    /* PTHREAD_SCOPE_SYSTEM(綁定)/ PTHREAD_SCOPE_PROCESS(非綁定) */
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
    /* PTHREAD_CREATE_DETACHED(分離)/ PTHREAD_CREATE_JOINABLE */
int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);
    /* SCHED_FIFO / SCHED_RR / SCHED_OTHER */
int pthread_attr_setschedparam(pthread_attr_t *attr, struct sched_param *param);
int pthread_attr_destroy(pthread_attr_t *attr);

SCHED_FIFO 允許線程一直執行,直到出現更高優先級的就緒線程或它自行阻塞;SCHED_RR 與之類似,但同優先級的就緒線程若已超過時間片,會觸發輪替。當 SCHED_FIFO 或 SCHED_RR 線程在同一條件變數或互斥量上等待時,會依優先級順序被喚醒。

其他屬性還包括守護區大小、繼承排程設定與堆疊位址/大小:

int pthread_attr_setguardsize(pthread_attr_t *attr, size_t guardsize);
int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);
int pthread_attr_setstack(pthread_attr_t *attr, void *stackaddr, size_t stacksize);
int pthread_attr_setstackaddr(pthread_attr_t *attr, void *stackaddr);
int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);

建立一個優先級 10 的線程:

pthread_attr_t attr;
struct sched_param param;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setschedpolicy(&attr, SCHED_RR);
param.sched_priority = 10;
pthread_attr_setschedparam(&attr, &param);
pthread_create(xxx, &attr, xxx, xxx);
pthread_attr_destroy(&attr);

脫離線程範例(thread5.c):

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

void *thread_function(void *arg);
char message[] = "Hello World!";
int thread_finished = 0;

int main()
{
    int res;
    pthread_t a_thread;
    pthread_attr_t thread_attr;

    pthread_attr_init(&thread_attr);
    pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
    res = pthread_create(&a_thread, &thread_attr, thread_function, (void *)message);
    if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); }
    pthread_attr_destroy(&thread_attr);

    while (!thread_finished) {
        printf("Waiting for thread to say it's finished...\n");
        sleep(1);
    }
    printf("Other thread finished, Bye!\n");
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg)
{
    printf("thread_function() is running. Argument was %s\n", (char *)arg);
    sleep(4);
    printf("Second thread setting finished flag, and exiting now\n");
    thread_finished = 1;
    pthread_exit(NULL);
}
gcc -D _REENTRANT thread5.c -o thread5 -lpthread

7. 取消線程

int pthread_cancel(pthread_t thread);
int pthread_setcancelstate(int state, int *oldstate);
    /* PTHREAD_CANCEL_ENABLE / PTHREAD_CANCEL_DISABLE */
int pthread_setcanceltype(int type, int *oldtype);
    /* PTHREAD_CANCEL_ASYNCHRONOUS:立即行動
       PTHREAD_CANCEL_DEFERRED:等到呼叫 pthread_join、pthread_cond_wait、
       pthread_testcancel、sem_wait 或 sigwait 之後才行動 */

預設狀態為 ENABLE + DEFERRED。範例(thread6.c)由主線程發送取消請求:

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

void *thread_function(void *arg)
{
    int i;
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
    printf("thread_function is running...\n");
    for (i = 0; i < 10; i++) {
        printf("Thread is still running (%d)...\n", i);
        sleep(1);
    }
    pthread_exit(0);
}

int main()
{
    int res;
    pthread_t a_thread;
    void *thread_result;

    pthread_create(&a_thread, NULL, thread_function, NULL);
    sleep(4);
    printf("Canceling thread...\n");
    res = pthread_cancel(a_thread);
    if (res != 0) { perror("Thread cancel failed"); exit(EXIT_FAILURE); }
    pthread_join(a_thread, &thread_result);
    printf("Thread canceled!\n");
    exit(EXIT_SUCCESS);
}

8. 多線程

同時建立多個線程並逐一回收(thread7.c):

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

#define NUM 6
void *thread_function(void *arg);

int main()
{
    int res, index;
    pthread_t a_thread[NUM];
    void *thread_result;

    for (index = 0; index < NUM; index++) {
        res = pthread_create(&a_thread[index], NULL, thread_function, (void *)index);
        if (res != 0) { perror("Thread create failed"); exit(EXIT_FAILURE); }
        sleep(1);
    }
    printf("Waiting for threads to finish...\n");
    for (index = NUM - 1; index >= 0; index--) {
        res = pthread_join(a_thread[index], &thread_result);
        if (res == 0) printf("Picked up a thread: %d\n", index + 1);
    }
    printf("All done\n");
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg)
{
    int my_number = (int)arg;
    int rand_num = 1 + (int)(9.0 * rand() / (RAND_MAX + 1.0));
    printf("thread_function is running. Argument was %d\n", my_number);
    sleep(rand_num);
    printf("Bye from %d\n", my_number);
    pthread_exit(NULL);
}
gcc -D _REENTRANT thread7.c -o thread7 -lpthread

9. 小結

本文涵蓋 Linux 環境下的多線程編程基礎:以 _REENTRANT 取得可重入能力、pthread 的建構與回收、以信號量與互斥量完成同步、透過屬性控制分離與排程、取消線程,以及多線程並發的組織方式。適合作為入門起點,更深入的條件變數、執行緒局部儲存與無鎖結構,可再另行延伸。

Copyright © Linux教程網 All Rights Reserved