#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_rtn)(void),
void *restrict arg);
Returns: 0 if OK, error number on failure
C99 中新增加了 restrict 修飾的指針: 由 restrict 修飾的指針是最初唯一對指針所指向的對象進行存取的方法,僅當第二個指針基於第一個時,才能對對象進行存取。對對象的存取都限定於基於由 restrict 修飾的指針表達式中。 由 restrict 修飾的指針主要用於函數形參,或指向由 malloc() 分配的內存空間。restrict 數據類型不改變程序的語義。 編譯器能通過作出 restrict 修飾的指針是存取對象的唯一方法的假設,更好地優化某些類型的例程。
第一個參數爲指向線程標識符的指針。
第二個參數用來設置線程屬性。
第三個參數是線程運行函數的起始地址。
最後一個參數是運行函數的參數。
下面這個程序中,我們的函數thr_fn不需要參數,所以最後一個參數設爲空指針。第二個參數我們也設爲空指針,這樣將生成默認屬性的線程。當創建線程成功時,函數返回0,若不爲0則說明創建線程失敗,常見的錯誤返回代碼爲EAGAIN和EINVAL。前者表示系統限制創建新的線程,例如線程數目過多了;後者表示第二個參數代表的線程屬性值非法。創建線程成功後,新創建的線程則運行參數三和參數四確定的函數,原來的線程則繼續運行下一行代碼。
#include<stdio.h>
#include<pthread.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
pthread_t ntid;
void printids(const char *s){
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int)tid,(unsigned
int)tid);
}
void *thr_fn(void *arg){
printids("new thread:");
return ((void *)0);
}
int main(){
int err;
err = pthread_create(&ntid,NULL,thr_fn,NULL);
if(err != 0){
printf("can't create thread: %s\n",strerror(err));
return 1;
}
printids("main thread:");
sleep(1);
return 0;
}
把APUE2上的一個程序修改一下,然後編譯。
結果報錯:
pthread.c:(.text+0x85):對‘pthread_create’未定義的引用
由於pthread庫不是Linux系統默認的庫,連接時需要使用庫libpthread.a,所以在使用pthread_create創建線程時,在編譯中要加-lpthread參數:
gcc -o pthread -lpthread pthread.c