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);
}
转载于:https://blog.51cto.com/leon1986/1322560