无法在C中编译多线程示例 在尝试为学校做多线程项目时遇到重大问题
我只是试着运行示例代码,看看pthread是如何工作的无法在C中编译多线程示例 在尝试为学校做多线程项目时遇到重大问题,c,multithreading,pthreads,C,Multithreading,Pthreads,我只是试着运行示例代码,看看pthread是如何工作的 #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 !
#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);
}
然后从命令行:
makeassn3
看来您还没有向链接器指定关于线程库的内容。对于多线程应用程序,gcc
的常用选项如下(假设程序文件名为thread1.c):
还建议使用-Wall-O3-pedantic errors
来迂腐地描述编译器警告等。因此这应该做到:
gcc -Wall -O3 -pedantic-errors -D_REENTRANT -lpthread thread1.c -o thread1
编译和链接时,您可能需要使用
-pthread
选项。我尝试过的方法:makefile all:gcc-Wall-O3-pedantic errors-D_REENTRANT-lpthread assn3.c-o assn3 all:gcc-g-Wall-pthread assn3.c assn3 makefile:'all:gcc-Wall-O3-pedantic errors-D_REENTRANT-lpthread assn3.c-o assn3'建议使用-pthread
而不是-lpthread
。这还将为您定义可重入的,以及线程所需的任何其他内容。它更便于携带。
gcc -D_REENTRANT -lpthread thread1.c -o thread1
gcc -Wall -O3 -pedantic-errors -D_REENTRANT -lpthread thread1.c -o thread1