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

Linux 多執行緒編程完全指南

基本概念

  • 原先指向 main() 的執行緒稱為主執行緒(main thread)。
  • 透過 pthread_create() 建立的執行緒稱為子執行緒(child thread)。
  • 主/子執行緒只有在建立時才有區別,建立完成後彼此獨立、地位平等,可交流、共享或私有,沒有上下級關係,這點與多進程類似。
  • 建立子執行緒後,兩者獨立運行,執行先後由 OS 調度演算法決定。
  • 執行緒既獨立又相互影響:主執行緒結束會導致進程結束,進程結束又會讓其所有執行緒結束。
  • 多執行緒共享一個進程,而進程只有一個輸出終端,因此需協調好輸出順序,否則部分輸出可能看不到。

常用模型

  • 取得 ThreadID:pthread_self()/pthread_equal()
  • 建立前設置屬性:pthread_attr_init() 等
  • 建立執行緒:pthread_create()
  • 已建立後設置:pthread_detach()/pthread_setcancelstate()/pthread_setcanceltype()
  • 發送訊號:pthread_kill()
  • 退出執行緒但不退出進程:pthread_exit()
  • 終止另一執行緒:pthread_cancel()
  • 等待某執行緒:pthread_join()
  • 編譯時加上 gcc -pthread

標頭檔

#include <pthread.h>

pthread_create()

// 在呼叫進程中建立新執行緒,透過啟動 start_routine() 開始執行,arg 是其唯一參數
// 成功返回 0,失敗返回 error number
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                   void *(*start_routine)(void *), void *arg);

thread:存放新執行緒 ID。
attr:執行緒屬性,給 NULL 表示預設。
start_routine:新執行緒的處理函數,執行完畢後執行緒終止。
arg:傳給 start_routine 的實參。

pthread_join()

// 等待 thread 指定的執行緒終止;若目標未終止則當前執行緒進入阻塞
// 成功返回 0,失敗返回 error number
int pthread_join(pthread_t thread, void **retval);

thread:執行緒編號。
retval:二級指標,用於帶回目標執行緒的退出狀態;若目標被 cancel,則帶回 PTHREAD_CANCELED。

完整示例

使用 pthread_create() 建立執行緒並以 pthread_join() 取得退出狀態:

// 使用 pthread_join 獲取目標執行緒的退出狀態
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
void* task(void* pv){
    char* pc = "hello";
    return (void*)pc;
}
main(){
    pthread_t thread;
    int error = pthread_create(&thread, NULL, task, NULL);
    if(0 != error) printf("%s", strerror(error)), exit(-1);
    char* ps = NULL;
    error = pthread_join(thread, (void**)&ps);
    if(0 != error) printf("pthread_join %s\n", strerror(error)), exit(-1);
    printf("child thread returned:%s\n", ps);
    return 0;
}

使用 pthread_exit() 只結束當前執行緒而不結束進程,並可帶出回傳值:

void* task(void* pv){
    static int i = 0;
    for(i = 1; i <= 20; i++){
        if(10 == i) pthread_exit((void*)&i); // 只結束當前執行緒
        else printf("i=%d\n", i);
    }
    return NULL;
}

使用 pthread_cancel() 取消指定執行緒,取消是否生效取決於執行緒的 state 與 type 屬性;若目標執行緒呼叫 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) 禁止取消,則取消請求不會生效。

Copyright © Linux教程網 All Rights Reserved