開始接觸 Linux 系統編程中的執行緒時,用 gcc sample.c 編譯會出現:
root@daoluan:/code/pthreadid# gcc sample.c
/tmp/cc1WztL9.o: In function `main':
sample.c:(.text+0x83): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
而且所有 pthread 相關函式都會報同樣的錯,導致編譯無法通過。
pthread 不是 Linux 預設連結的函式庫。連結階段找不到 pthread 庫中各函式的入口位址,連結自然失敗。
編譯時加上 -lpthread:
root@daoluan:/code/pthreadid# gcc -lpthread sample.c
root@daoluan:/code/pthreadid# ./a.out
main thread: pid 7059 tid 3078141632 (0xb778b6c0)
new thread: pid 7059 tid 3078138736 (0xb778ab70)
寫法上建議把參數放在原始檔後面(gcc sample.c -lpthread),因為部分連結器版本對參數順序敏感。
#include <stdio.h>
#include <pthread.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(void) {
int err;
err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0)
printf("pthread_create error \n");
printids("main thread:");
sleep(1);
return 0;
}
順帶一提,pthread_create 的失敗是透過回傳值(errno 碼)回報,而不是設定 errno,所以判斷方式與多數系統呼叫不同。