- 論壇徽章:
- 0
|
今天開始學習linux下用C開發(fā)多線程程序,Linux系統(tǒng)下的多線程遵循POSIX線程接口,稱為pthread。
#include
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 修飾的指針是最初唯一對指針所指向的對象進行存取的方法,僅當?shù)诙䝼指針基于第一個時,才能對對象進行存取。對對象的存取都限定于基于由 restrict 修飾的指針表達式中。 由 restrict 修飾的指針主要用于函數(shù)形參,或指向由 malloc() 分配的內存空間。restrict 數(shù)據(jù)類型不改變程序的語義。 編譯器能通過作出 restrict 修飾的指針是存取對象的唯一方法的假設,更好地優(yōu)化某些類型的例程。
第一個參數(shù)為指向線程標識符的指針。
第二個參數(shù)用來設置線程屬性。
第三個參數(shù)是線程運行函數(shù)的起始地址。
最后一個參數(shù)是運行函數(shù)的參數(shù)。
下面這個程序中,我們的函數(shù)thr_fn不需要參數(shù),所以最后一個參數(shù)設為空指針。第二個參數(shù)我們也設為空指針,這樣將生成默認屬性的線程。當創(chuàng)建線程成功時,函數(shù)返回0,若不為0則說明創(chuàng)建線程失敗,常見的錯誤返回代碼為EAGAIN和EINVAL。前者表示系統(tǒng)限制創(chuàng)建新的線程,例如線程數(shù)目過多了;后者表示第二個參數(shù)代表的線程屬性值非法。創(chuàng)建線程成功后,新創(chuàng)建的線程則運行參數(shù)三和參數(shù)四確定的函數(shù),原來的線程則繼續(xù)運行下一行代碼。
#includestdio.h>
#includepthread.h>
#includestring.h>
#includesys/types.h>
#includeunistd.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系統(tǒng)默認的庫,連接時需要使用庫libpthread.a,所以在使用pthread_create創(chuàng)建線程時,在編譯中要加-lpthread參數(shù):
本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u3/106123/showart_2163029.html |
|