筆者一直在學習unix環境高級編程。第十一章爲線程編程。第一個程序就是打印線程ID。程序以下:編程
[cpp] view plaincopy函數
#include "apue.h" 學習
#include <pthread.h> ui
pthread_t ntid; spa
void printids(const char* s) .net
{ 線程
pid_t pid; unix
pthread_t tid; blog
pid=getpid();//獲得當前進程id 進程
tid=pthread_self();//獲得當前線程id
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)
err_quit("can't create thread:%s\n",strerror(err));
printids("main thread :");
sleep(1);
exit(0);
}
編譯命令:gcc -o pro_11.1 pro_11-1.c
就會報錯:錯誤以下:
[cpp] view plaincopy
/tmp/ccAmLjR7.o: In function `main':
pro_11-1.c:(.text+0x307): undefined reference to `pthread_create'
collect2: ld ·µ»Ø 1
通過網上查詢緣由是:
pthread 庫不是 Linux 系統默認的庫,鏈接時須要使用靜態庫 libpthread.a,因此在使用pthread_create()建立線程,以及調用 pthread_atfork()函數創建fork處理程序時,須要連接該庫。
問題解決:
在編譯中要加 -lpthread參數
我用以下編譯命令:
[cpp] view plaincopy
gcc -o pro_11.1 pro_11-1.c -lpthread
程序輸出結果:
[cpp] view plaincopy
main thread : pid 6123 tid 3086358208 (0xb7f616c0)
new thread: pid 6123 tid 3086355344 (0xb7f60b90)