Linux多線程函數解析

  Linux多線程函數解析
Linux多線程函數用得比較多的是下面的3個
pthread_create(),pthread_exit(),pthread_join();它們都是在頭文件<pthread.h>之中。編譯時需要加靜態庫-lpthread

 

下面是函數的說明:
  pthread_create是UNIX環境創建線程函數
int pthread_create(
      pthread_t *restrict tidp,
      const pthread_attr_t *restrict_attr,
      void*(*start_rtn)(void*),
      void *restrict arg);
返回值
  若成功則返回0,否則返回出錯編號
  返回成功時,由tidp指向的內存單元被設置爲新創建線程的線程ID。attr參數用於制定各種不同的線程屬性。新創建的線程從start_rtn函數的地址開始運行,該函數只有一個萬能指針參數arg,如果需要向start_rtn函數傳遞的參數不止一個,那麼需要把這些參數放到一個結構中,然後把這個結構的地址作爲arg的參數傳入。
  linux下用C開發多線程程序,Linux系統下的多線程遵循POSIX線程接口,稱爲pthread。
  由 restrict 修飾的指針是最初唯一對指針所指向的對象進行存取的方法,僅當第二個指針基於第一個時,才能對對象進行存取。對對象的存取都限定於基於由 restrict 修飾的指針表達式中。 由 restrict 修飾的指針主要用於函數形參,或指向由 malloc() 分配的內存空間。restrict 數據類型不改變程序的語義。 編譯器能通過作出 restrict 修飾的指針是存取對象的唯一方法的假設,更好地優化某些類型的例程。
參數
  第一個參數爲指向線程標識符的指針。
  第二個參數用來設置線程屬性。
  第三個參數是線程運行函數的起始地址。
  最後一個參數是運行函數的參數。
另外,在編譯時注意加上-lpthread參數,以調用靜態鏈接庫。因爲pthread並非Linux系統的默認庫


pthread_exit(void* retval);
線程通過調用pthread_exit函數終止自身執行,就如同進程在結束時調用exit函數一樣。這個函數的作用是,終止調用它的線程並返回一個指向某個對象的指針。該指針可以通過pthread_join(pthread_t tpid, void **value_ptr)中的第二個參數value_ptr獲取到。

 

函數pthread_join用來等待一個線程的結束。函數原型爲:
  extern int pthread_join __P (pthread_t __th, void **__thread_return);
第一個參數爲被等待的線程標識符,第二個參數爲一個用戶定義的指針,它可以用來存儲被等待線程退出時的返回值。這個函數是一個線程阻塞的函數,調用它的函數將一直等待到被等待的線程結束爲止,當函數返回時,被等待線程的資源被收回。如果執行成功,將返回0,如果失敗則返回一個錯誤號。
所有線程都有一個線程號,也就是Thread ID。其類型爲pthread_t。通過調用pthread_self()函數可以獲得自身的線程號。

 


下面是一個簡單的例子,子線程thread_fun會打出5次“this is thread_fun print!”然後調用pthread_exit退出,並返回一個指向字符串“this is thread return value!”的指針。在主函數裏面調用pthread_join等待thread_fun線程結束,然後讀取子線程的返回值到value中,再打印出來。
輸出結果是:
pthread_create ok!
this is thread_fun print!
this is thread_fun print!
this is thread_fun print!
this is thread_fun print!
this is thread_fun print!
pthread exit value: this is thread return value!

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <pthread.h>
//////////////////////////////////////////////////////
void *thread_fun(void *arg) {
    int i=0;
    char *value_ptr = "this is thread return value!\n";
    for (i=0; i<5; i++) {
        printf("this is thread_fun print!\n");
        sleep(1);
    }
    pthread_exit((void*)value_ptr);
}
//////////////////////////////////////////////////////
int main(int argc, char **argv) {
    pthread_t pid;
    int ret;
    void* value;

    ret = pthread_create(&pid, NULL, thread_fun, NULL);
    if (ret) {
        printf("pthread_create failed!\nerrno:%d\n", errno);
        return -1;
    }
    printf("pthread_create ok!\n");

    pthread_join(pid, &value);
    printf("pthread exit value: %s\n", value);
    return 0;
}

 

發佈了79 篇原創文章 · 獲贊 6 · 訪問量 91萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章