[英]Cannot compile multi-threading example in C
我只是試圖運行示例代碼以查看pthreads的工作方式
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum;
void *runner(void *param);
int main(int argc, char *argv[]) {
pthread_t tid;
pthread_attr_t attr;
if (argc !=2){
fprintf(stderr, "usage: a.out <interger value>\n");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, "%d must be >= 0\n",atoi(argv[1]));
return -1;
}
pthread_attr_init(&attr);//get default attributes
pthread_create(&tid,&attr,runner,argv[1]);//create the thread
pthread_join(tid,NULL);//wait for the thread to exit
printf("sum = %d\n",sum);
}
void *runner(void *param) {
int i, upper = atoi(param);
sum = 0;
for (i =1; i <= upper; i++) {
sum += i;
}
pthread_exit(0);
}
而且無論我做什么,我都無法編譯代碼。 我收到以下錯誤:
運行“ /home/ubuntu/workspace/primefactor/assn3.c”/tmp/cc58AE5c.o:在函數“ main”中:assn3.c :(。text + 0xc4):未定義對“ pthread_create”的引用assn3.c :( .text + 0xd5):對“ pthread_join” collect2的未定義引用:錯誤:ld返回1退出狀態進程退出,代碼為:1
我試着用-pthread標志寫我自己的makefile。 沒用...。我嘗試跑步
sudo apt-get安裝libpthread-stubs0-dev
安裝正確的庫; 沒用...
我竭盡全力嘗試使pthreads_create()和pthreads_join()正常工作,它們是我學校項目的主要要求。 我已經使該項目與普通的C程序一起工作(從命令行獲取數字,獲取每個arg的素數,將它們存儲在數組中,然后傳遞該數組並顯示結果。例如:./ prime。 co {1..100}將通過BASH運行,並且輸出為1:1 2:2 3:3 4:2 2等等...所以這應該是輸出,我應該使用線程化,但是如果我什至不能編譯示例代碼來查看線程如何工作,我就無法做到。
我確實已經花了幾個小時進行搜索,嘗試,但是沒有擺脫pthread_create()和pthread_join()的這些未定義參考錯誤的運氣。 在弄清楚為什么我得到上述錯誤的任何幫助將不勝感激。
編輯:
感謝那些嘗試為我回答的人。 我不知道為什么我要投反對票。 我在這里不是很活躍,在尋求幫助時我會盡量保持禮貌。 無論如何,我終於想通了。
如果我使用的是make文件,則它必須如下所示:
assn3:
gcc -g -Wall -pthread assn3.c -o assn3
然后從命令行: make assn3
似乎您尚未指定有關線程庫的鏈接器。 對於多線程應用程序,下面是gcc
的通常選項(假設您的程序文件名為thread1.c):
gcc -D_REENTRANT -lpthread thread1.c -o thread1
它也建議使用-Wall -O3 -pedantic-errors
是迂腐約編譯器警告等,所以這應該這樣做:
gcc -Wall -O3 -pedantic-errors -D_REENTRANT -lpthread thread1.c -o thread1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.