在linux C 中调用pthread_create()函数出现undefined reference to 'pthread_create‘
#include <pthread.h>
#include <stdio.h>
#define N 2
void *thread(void * vargp);
char **ptr;
int main(void) {
int i;
pthread_t tid;
char *msg[]={
"Hello laopo1",
"Hello laopo2"
};
ptr=msg;
for(i=0;i<N;i++)
pthread_create(&tid,NULL,thread,(void *)i);
pthread_exit(NULL);
return 0;
}
void * thread(void *vargp){
int myid=(int)((int *)vargp);
static int count=0;
fprintf(stdout,"[%d]:%s (count=%d)\n",myid,ptr[myid],++count);
return NULL;
}
经过网上查询原因是:
pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
问题解决:
在编译中要加 -lpthread参数
我用如下编译命令:
gcc -o lala haha.c -lpthread