Process 編程調試

process.c:(.text+0xf5): undefined reference to `pthread_create'

process.c:(.text+0x133): undefined reference to `pthread_join'

collect2: error: ld returned 1 exit status


線程程序編譯過程中,出現以上報錯。百思不解其解。


轉自http://www.shangxueba.com/jingyan/84321.html

問題原因:

pthread 庫不是 Linux 系統默認的庫,連接時需要使用靜態庫 libpthread.a,所以在使用pthread_create()創建線程,以及調用 pthread_atfork()函數建立fork處理程序時,需要鏈接該庫。

問題解決:

在編譯中要加 -lpthread參數

gcc thread.c -o thread -lpthread

thread.c爲你些的源文件,不要忘了加上頭文件#include

以上運行成功。代碼如下:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int nthreads = 1;       /* 線程執行函數,傳入參數爲線程序號,傳出參數爲項: (序號+1) */
void *dowork (void *params)
{
        int j = *(int *)params;
        int term = j+1;
        *(int *)params = term;
        printf ("the thread [%d]: term =%d\n",j,term);
}
void main(int argc,char **argv)
{
        int i;
        pthread_t threads[100];
        int pthread_data[100];
        float mean = 0;         /* 平均數 */
        float variance = 0; /* 方差 */
        if(argc==2)
                nthreads = atoi (argv[1]); /* 將命令行字符串參數轉換爲整數 */
                for (i=0; i<nthreads; i++) {
                pthread_data [i] = i ;
                pthread_create(&threads[i],NULL,dowork,&pthread_data[i]);            /* 創建線程 */
        }
        for (i=0; i<nthreads; i++) {
                pthread_join (threads [i], NULL);                       /* 等待子線程結束,匯合結果 */
                mean +=(float)pthread_data[i];
        }
        mean = mean / nthreads;
        for(i=0; i<nthreads; i++) {
                variance += (float)(pthread_data[i]-mean)*(pthread_data[i]-mean);
        }
        variance = variance / nthreads;
        printf("The total threads is %d\n",nthreads);
        printf("The mean = %f\n", mean);
        printf("The variance = %f\n",variance);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章